package com.stylefeng.guns.modular.huamao.service.impl;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.CacheUtil;
import com.stylefeng.guns.modular.huamao.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.common.GetOrderNum;


/**
 * <p>
 * 会员账户表 服务实现类
 * </p>
 *
 * @author gxz123
 * @since 2018-04-11
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {
	@Autowired
	private AccountMapper am;
	@Autowired
	private LogCashMapper logCashMapper;
	@Autowired
	private AccountOperationMapper accountOperationMapper;
	@Autowired
	private SktSysConfigsMapper sktSysConfigsMapper;
	@Autowired
	GoodsMapper goodsMapper;
	@Autowired
	private LogCashFreezeMapper logCashFreezeMapper;
	@Autowired
	LogKaiyuanMapper  logKaiyuanMapper;
	@Autowired
	SktOrdersMapper ordersMapper;
    @Autowired
    private UsersRechargeMapper usersRechargeMapper;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private LogScoreMapper logScoreMapper;
	@Autowired
	private AccountShopMapper accountShopMapper;
	@Autowired
	private LogKaiyuanTurnoverMapper logKaiyuanTurnoverMapper;
	@Autowired
	private UsersUpgradeMapper usersUpgradeMapper;
    @Autowired
    private SktOrdersStockscoreMapper sktOrdersStockscoreMapper;
	@Autowired
	private SktSysConfigsMapper sysConfigsMapper;
	@Autowired
	private LogKaiyuanFreezeMapper logKaiyuanFreezeMapper;
	@Autowired
	private SktBuyplaqueMapper sktBuyplaqueMapper;
	@Autowired
	private LogScoreFreezeMapper logScoreFreezeMapper;
	@Autowired
	private LogScoreSpecialMapper logScoreSpecialMapper;
    @Autowired
    private IUsersService usersService;
	@Autowired
	private AgentsApplysMapper agentsApplysMapper;
	@Autowired
	private SktAgentsStockholderMapper agentsStockholderMapper;
    @Autowired
    private SktAgentsMapper agentsMapper;
	@Autowired
	private  SktDateTransformMapper sktDateTransformMapper;
	@Autowired
    private LogStockscoreMapper logStockscoreMapper;
	@Autowired
	private SktAgentsAccountMapper sktAgentsAccountMapper;
	@Autowired
	private LogScoreAgentMapper logScoreAgentMapper;
	@Autowired
	private LogKaiyuanAgentMapper logKaiyuanAgentMapper;
	@Autowired
	private SktAgentsStockholderMapper sktAgentsStockholderMapper;
	@Autowired
	private SktShopsMapper sktShopsMapper;
    @Autowired
    private  SktAgentsAccountMapper agentsAccountMapper;
    @Autowired
	private SktSalesMonthMapper sktSalesMonthMapper;
	@Autowired
	private SktSalesMonthMapper sktsalesMonthService;
	@Autowired
	private IUsersUpgradeService  usersUpgradeService;

	@Autowired
	private  UsersRealnameMapper  usersRealnameMapper;
	@Autowired
	private  SktOrdersExtensionMapper  SktOrdersExtensionMapper;
	@Autowired
	private ISktOrdersExtensionService sktOrdersExtensionService;
	@Autowired
	private IGoodsSpecsService goodsSpecsService;
	@Autowired
	private IAccountShopService  accountShopService;
	@Autowired
	private ISktAccountSystemService sktAccountSystemService;
	@Autowired
	private ISktOrdersStoresService sktOrdersStoresService;
    @Autowired
    private IMessagesService messagesService;
    @Autowired
    private ISktShopsService sktShopsService;
	@Autowired
	private SktOrdersStoresMapper sktOrdersStoresMapper;
    @Autowired
    private LogOrdersMapper  logOrdersMapper;
	@Autowired
	private CacheUtil cacheUtil;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IShoppingService shoppingService;
	@Autowired
	private ILogThirdpayService logThirdpayService;
	@Autowired
	private ISktOrderReviewService sktOrderReviewService;
	// 展示用户账户列表
	@Override
	public List<AccountList> selectAccountAll(AccountList accountList) {
		return am.selectAccountAll(accountList);
	}

	// 给用户添加相应的积分,并且判断是否升级的是经理，直接分享人，直接分享人类型
//	@Transactional
//	@Override
//	public String upAfterAdd(Integer userId, Boolean isManager, Users shareMan, Integer orderId, BigDecimal score,
//							 Integer type, String remark) {
//
//		/**
//		 * 给用户添加积分
//		 */
//		LogScore logScore = new LogScore();
//
//		// 支出人为平台设置为0
//		logScore.setFromId(0);
//		// 收入人为此用户
//		logScore.setUserId(userId);
//		// 积分类型为 用户升级 7
//		logScore.setType(type);
//		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
//		logScore.setOrderNo("3" + strDate + num);
//		// 操作前金额要到数据库查询account表中的实时金额，将userId传过去
//		Account account = am.findScoreById(userId);
//		// 用户操作前金额
//		logScore.setPreScore(account.getScore());
//		// 流水标志：加积分所以类型为 1
//		logScore.setScoreType(1);
//		// 操作金额
//		logScore.setScore(score);
//		// 备注直接生成
//		logScore.setRemark(remark);
//		// 创建时间
//		logScore.setCreateTime(new Date());
//		// 添加积分记录
//		Integer insert = logScoreMapper.insert(logScore);
//
//		/**
//		 * 调用修改用户账户的方法，并传过去一个值，告诉发放是添加积分，还是待发转入，
//		 */
//		// Account account3 = am.findFreezeScoreById(userId);
//		Integer update = this.updateScoreByUserId(account, score);
//
//		// 实时查询用户账户
//		// Account account2 = am.findFreezeScoreById(userId);
//
//		/**
//		 * 判断此用户是否有代发积分，如果有的话转入正式积分
//		 */
//		if (account.getFreezeScore().compareTo(BigDecimal.ZERO) != 0) {
//			/**
//			 * 将代发积分转入正式
//			 */
//			this.FreezeToFormal(userId, account.getFreezeScore(), isManager);
//			//待发记录生成
//			this.insertLogScoreFreeze(0,31,"3",account.getFreezeScore(),"待发积分，划拨到正式",account.getFreezeScore(),-1,userId);
//		}
//
//		/**
//		 * 判断此用户是否有待发现金，有的话转入正式
//		 */
//		if (account.getFreezeCash().compareTo(BigDecimal.ZERO) != 0) {
//
//			/**
//			 * 将待发现金转入正式
//			 */
//			this.cashFrrezeToFormal(userId, account.getFreezeCash(), isManager);
//			//升级经理
//			if(isManager){
//				//现金待发记录
//				this.freezeCashToFormal(31,0,userId,"3",account.getFreezeCash(),-1,account.getFreezeCash(),"普通用户升级为经理，待发现金转为可用现金");
//			}else{
//				//现金待发记录
//				this.freezeCashToFormal(31,0,userId,"3",account.getFreezeCash(),-1,account.getFreezeCash(),"普通用户升级为主管，待发现金转为可用现金");
//			}
//		}
//
//		/**
//		 * 判断此用户是否是商家
//		 */
//		AccountShop accountShop = accountShopMapper.findShopId(userId);
//		if (accountShop != null && accountShop.getShopId() != 0) {
//			// 判断商家是否有待发华宝营业额
//			if (accountShop.getFreezeKaiyuan() != null
//					&& accountShop.getFreezeKaiyuan().compareTo(BigDecimal.ZERO) != 0) {
//				/**
//				 * 将待发华宝转入正式账户
//				 */
//				// 判断用户升级经理还是主管
//				if (isManager) {
//					remark = "普通用户升级为经理，待发华宝营业额转为可用华宝营业额";
//				} else {
//					remark = "普通用户升级为主管，待发华宝营业额转为可用华宝营业额";
//				}
//				// 生成华宝营业额流水表
//				this.hbTurnover(4, userId, userId, "3", 1, accountShop.getFreezeKaiyuan(), remark);
//
//			}
//
//		}
//
//		/**
//		 * 是否升级的是经理，如果是经理，查询七个工作日内是否有下线升级为代理
//		 */
//		if (isManager) {
//			// 判断是否有下线
//			List<Integer> downWires = usersMapper.findDownWires(userId);
//			//如果有下线判断是否七个工作日内有升级为代理的
//			if(downWires.size() > 0){
//				List<AgentsApplys> agents = getAgentsApplysSevenAgo(userId);
//				if (agents != null && agents.size() > 0) {
//					BigDecimal sumScore = BigDecimal.ZERO;
//					BigDecimal sumScoreFreeze =
//							BigDecimal.ZERO;
//					for (AgentsApplys AgentsApply : agents) {
//						if (AgentsApply.getType() == 7) {
//							sumScore = sumScore.add
//									(AgentsApply.getMoney().multiply(new BigDecimal("200")));
//						} else if (AgentsApply.getType() !=
//								7 && AgentsApply.getType() != 6) {
//							sumScoreFreeze =
//									sumScoreFreeze.add(AgentsApply.getMoney().multiply(new BigDecimal("200")));
//						}
//					}
//					if(sumScoreFreeze.compareTo(BigDecimal.ZERO)==1){
//						this.insertLogScoreFreeze(0, 10, "4",
//								account.getFreezeScore(), "下线升级代理奖励", sumScoreFreeze, 1, userId);
//						account.setFreezeScore
//								(account.getFreezeScore().add(sumScoreFreeze));
//					}
//					if(sumScore.compareTo(BigDecimal.ZERO)==1){
//						this.insertLogScore(0, 10, "4",
//								account.getScore(), "下线升级代理奖励", sumScore, 1, userId);
//						account.setScore(account.getScore().add
//								(sumScore));
//						account.setTotalScore
//								(account.getTotalScore().add(sumScore));
//					}
//					am.updateById(account);
//				}
//			}
//		}
//        // 查询用户升级前后角色
//        UsersUpgrade usersUpgrade = usersUpgradeMapper.findUserRole(orderId);
//		/**
//		 * 判断直接分享人是否为空，直接分享人，现金奖励
//		 */
//		if (shareMan.getUserId() != null) {
//			// 普通》主管 。 普通》 经理 。 主管》经理
//			if (usersUpgrade.getPreRole() == 0 && usersUpgrade.getAfterRole() == 1) {
//				//查询商城配置中分享人应得现金奖励
//				SktSysConfigs configs = sktSysConfigsMapper.selectSysConfigsByFieldCode("directorProfit");
//				// 实时查询用户账户余额
//				Account findScoreById = am.findScoreById(shareMan.getUserId());
//				// 判断用户是否为普通用户
//				if (shareMan.getUserType() == 0) {
//					// 存入待发现金账户
//					this.freezeCashToFormal(1, userId, shareMan.getUserId(), "3", findScoreById.getFreezeCash(), 1,
//							new BigDecimal(configs.getFieldValue()), "被邀请人升级奖励");
//					// 修改用户账户待发现金
//					this.updateFreezeCash(findScoreById, new BigDecimal(configs.getFieldValue()));
//				} else {
//					// 存入正式现金账户
//					this.insertLogCash(1, userId, shareMan.getUserType(), "3", findScoreById.getCash(), "被邀请人升级奖励", 2,
//							new BigDecimal(configs.getFieldValue()));
//					// 修改用户账户
//					this.updateCash(findScoreById, new BigDecimal(configs.getFieldValue()));
//				}
//			} else if (usersUpgrade.getPreRole() == 0 && usersUpgrade.getAfterRole() == 2) {
//				//查询商城配置中分享人应得现金奖励
//				SktSysConfigs configs = sktSysConfigsMapper.selectSysConfigsByFieldCode("commonProfit");
//				// 实时查询用户账户余额
//				Account findScoreById = am.findScoreById(shareMan.getUserId());
//				// 判断用户是否为普通用户
//				if (shareMan.getUserType() == 0) {
//					// 存入待发现金账户
//					this.freezeCashToFormal(1, userId, shareMan.getUserId(), "3", findScoreById.getFreezeCash(), 1,
//							new BigDecimal(configs.getFieldValue()), "被邀请人升级奖励");
//					// 修改用户账户待发现金
//					this.updateFreezeCash(findScoreById, new BigDecimal(configs.getFieldValue()));
//				} else {
//					// 存入正式现金账户
//					this.insertLogCash(1, userId, shareMan.getUserType(), "3", findScoreById.getCash(), "被邀请人升级奖励", 2,
//							new BigDecimal(configs.getFieldValue()));
//					// 修改用户账户
//					this.updateCash(findScoreById, new BigDecimal(configs.getFieldValue()));
//				}
//			} else {
//				//查询商城配置中分享人应得现金奖励
//				SktSysConfigs configs = sktSysConfigsMapper.selectSysConfigsByFieldCode("managerProfit");
//				// 实时查询用户账户余额
//				Account findScoreById = am.findScoreById(shareMan.getUserId());
//
//				/**
//				 *因为这步是从主管升到经理已经给他的上线经理人 发展人数增加过一次，所以这里不做操作应该
//				 *先给inviteNum减一，下边会加回来相当于没有操作
//				 */
//				findScoreById.setInviteNum(findScoreById.getInviteNum()-1);
//				// 判断用户是否为普通用户
//				if (shareMan.getUserType() == 0) {
//					// 存入待发现金账户
//					this.freezeCashToFormal(1, userId, shareMan.getUserId(), "3", findScoreById.getFreezeCash(), 1,
//							new BigDecimal(configs.getFieldValue()), "被邀请人升级奖励");
//					// 修改用户账户待发现金
//					this.updateFreezeCash(findScoreById, new BigDecimal(configs.getFieldValue()));
//				} else {
//					// 存入正式现金账户
//					this.insertLogCash(1, userId, shareMan.getUserType(), "3", findScoreById.getCash(), "被邀请人升级奖励", 2,
//							new BigDecimal(configs.getFieldValue()));
//					// 修改用户账户
//					this.updateCash(findScoreById, new BigDecimal(configs.getFieldValue()));
//				}
//			}
//		}
//        /**
//         * 判断用户是否是从普通升主管或是经理
//         */
//        //不是主管=》经理
//        if (usersUpgrade.getPreRole() != 1){
//            //调用方法查看是否有代发奖励，和发展人数
//            this.selectSpecial(userId,isManager);
//        }
//		// if (insert == 1 && update == 1) {
//		// return "success";
//		// }
//		return null;
//	}
    /**
	 * @param account
	 *            用户账户表
	 * @param cash
	 *            用户添加的积分
	 * @param isFreezeTo
	 *            判断是否是待发转入正式，如果是待发转入正式，待发清零，如果是正式的话，先在这个里边清空，让他在走sql是不修改
	 * @return
	 */
	public Integer updateScoreByUserId(Account account, BigDecimal score) {
		/**
		 * 用户账户表中增加积分
		 */
		// 将用户账户表中积分添加变化金额
		account.setScore(account.getScore().add(score));
		// 将用户获得的积分添加到用户累计获得中去
		account.setTotalScore(account.getTotalScore().add(score));
		// 判断现金是否为空
		// if (cash != null) {
		// // 将用户账户表中积分添加变化金额
		// account.setCash(account.getCash().add(cash));
		// // 将用户获得的积分添加到用户累计获得中去
		// account.setTotalCash(account.getTotalCash().add(cash));
		// }
		// 判断是正常的添加积分，还是待发转入，如果是待发转入，将待发修改成0，不是 待发就改为空
		// if (isFreezeTo) {
		// account.setFreezeScore(new BigDecimal(0));
		// }
		// 判断是否待发转入，如果是待发转入，将待发修改成0，不是待发就改为空
		// if (account.getFreezeCash() != null) {
		// account.setFreezeCash(new BigDecimal(0));
		// }
		// 修改用户账户
		Integer update = am.updateByUserId(account);
		return update;
	}

	@Override
	public Account selectAccountByuserId(Integer userId) {
		// TODO Auto-generated method stub
		return am.selectAccountByuserId(userId);
	}
	/** 用户点击升级
	 * @param userId   用户id
	 * @return
	 */
	@Override
	public JSONObject getUseUpDate(Integer userId) {
		// TODO Auto-generated method stub
		JSONObject json=new JSONObject();
		Users users = usersService.selectById(userId);
		if(users!=null){
			int userType=users.getUserType();
			if(userType==0){
				json.put("upAgentAccount", "997.00");
				json.put("upAgentScore", "99700.00");
				json.put("upManagerAccount", "9997.00");
				json.put("upManagerScore", "999700.00");
			}else if(userType==1 ){
				json.put("upManagerAccount", "9000.00");
				json.put("upManagerScore", "900000.00");
			}
			json.put("code", "01");
			json.put("msg", "成功");
		}else{
			json.put("code", "00");
			json.put("msg", "用户不存在");
		}
		return json;
	}

	/**
	 *用户升级输入密码支付
	 * @param usersUpgrade
	 * @param payPwd
	 * @return
	 */
    @Transactional
	@Override
	public JSONObject updateByUp(UsersUpgrade usersUpgrade,String payPwd) {
		JSONObject json = new JSONObject();
    	Integer userId=usersUpgrade.getUserId();
        JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);
        if ("00".equals(jsonObject.get("code"))){
            return jsonObject;
        }else {
            try {
                Map<String, Object> map = this.getAfterSevenWorkDay(7);
                String  endDays=map.get("endDay").toString().substring(0,10);
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                String time = format.format(new Date());
                String  newTime=endDays+" "+time;
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                Date newDate  = sdf.parse(newTime);
                usersUpgrade.setStatus(1);
                //平台现金账户支付金额也赋值到realmoney字段
                if (usersUpgrade.getCash().compareTo(BigDecimal.ZERO)==1){
					usersUpgrade.setRealMoney(usersUpgrade.getCash());
				}
//                usersUpgrade.setUpgradeTime(newDate);
				usersUpgrade.setUpgradeTime(new Date());
                //	usersUpgrade.setPayType(payType);
                usersUpgradeMapper.updateById(usersUpgrade);
                Account account = am.selectAccountByuserId(userId);
                Integer payType=usersUpgrade.getPayType();
                if (payType==2){

					BigDecimal cash=account.getCash();
					BigDecimal cashUpgrade=usersUpgrade.getCash();
					if (cashUpgrade.compareTo(cash)==1){
						json.put("code","00");
						json.put("msg","现金账户余额不足无法升级");

					}
                    // 生成现金流水
                    this.insertLogCash(-1, 0, userId, usersUpgrade.getOrderNo(), account.getCash(), "用户升级", 35, usersUpgrade.getCash());
                    // 修改现金账户
                    account.setCash(account.getCash().subtract(usersUpgrade.getCash()));
                }

                am.updateCash(account);
                json.put("code","01");
                json.put("msg","下单成功");

            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                json.put("code","00");
                json.put("msg","下单失败");

            }
            return  json;
        }
	}
	/*
	 * 取消用户升级
	 *
	 */
    @Transactional
	public boolean resetUPGrade(UsersUpgrade usersUpgrade) {
		try {
			Account account = am.selectAccountByuserId(usersUpgrade.getUserId());
			//生成现金流水
			this.insertLogCash(1, 0, usersUpgrade.getUserId(), "3", account.getCash(), "用户升级", 35, usersUpgrade.getCash());
			BigDecimal cash2 = account.getCash().add(usersUpgrade.getCash());
			account.setCash(cash2);
			am.updateAccount(account);
			return true;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
	}


    @Override
    public String selectSpSorceByUserId(Integer userId, String type) {
        String sorce="0.000";
        if("1".equals(type)){
            sorce =  am.selectSpSorceByUserIdline(userId);
        }else{
            sorce = am.selectSpSorceByUserIdUm(userId);
        }
        return sorce;
    }

    //充值后，现金账户添加现金
    @Transactional
    @Override
    public JSONObject rechargeAfter(UsersRecharge recharge) {
        JSONObject json = new JSONObject();
        //修改充值状态
        recharge.setStatus(1);
        Integer update1 = usersRechargeMapper.updateById(recharge);
        //查询充值订单信息
        recharge = usersRechargeMapper.selectOne(recharge);
        //实时查询账户余额
        Account account = am.findScoreById(recharge.getUserId());
        //生成现金流水
        this.insertLogCash(1, recharge.getUserId(), recharge.getUserId(), recharge.getOrderNo(), account.getCash(), "用户充值", 1, recharge.getCash());
        //给用户账户添加现金，累计现金
        account.setCash(account.getCash().add(recharge.getCash()));
        account.setTotalCash(account.getTotalCash().add(recharge.getCash()));
        Integer update = am.updateByUserId3(account);
        json.put("code", "01");
        json.put("msg", "充值成功！");
        return json;
    }

    //申请库存积分前操作
    @Override
    public String applyStockBefore() {
            //查询购买赠送比例
            SktSysConfigs buyStockScore = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScorePrice");
            return buyStockScore.getFieldValue();
    }

    //是否在购买时间段内，如果在继续操作，不在结束
    @Override
    public JSONObject isBuyTime(Integer shopId, BigDecimal cash) {
        JSONObject json = new JSONObject();
        //判断用户是否允许购买库存积分
		SktShops sktShops1 = sktShopsService.selectById(shopId);
		Integer usersId=sktShops1.getUserId();
		Users users=usersService.selectById(usersId);
		int isOperation=users.getIsOperation();
		if (isOperation==0){
			json.put("code", "00");
			json.put("msg", "该功能已关闭！");
		}
        //查询购买赠送比例
        SktSysConfigs buyStockScore = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScorePrice");
        //查询申请库存积分开始时间
        SktSysConfigs beginTime = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScoreStart");
        // 查询申请结束时间
        SktSysConfigs endTime = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScoreEnd");
        //查询当前时间并转换成相应格式
        SimpleDateFormat sfDate = new SimpleDateFormat("HHmmss");
        String strDate = sfDate.format(new Date());
        int date = Integer.parseInt(strDate);
        int end = Integer.parseInt(endTime.getFieldValue());
        //传来的end为小时，没显示分、秒，加上为了和现在时间做比较
        String end2 = end + "0000";
        end = Integer.parseInt(end2);
        int begin = Integer.parseInt(beginTime.getFieldValue());
        //传来的begin为小时，没显示分、秒，加上为了和现在时间做比较
        String begin2 = begin + "0000";
        begin = Integer.parseInt(begin2);
        //判断是否在允许购买时间段内
        if (date <= end && date >= begin) {
            //如果在的话，就查询账户余额
			SktShops sktShops = sktShopsMapper.selectById(shopId);
			Integer userId = sktShops.getUserId();
			AccountShopDTO accountShopDTO = accountShopMapper.findAccountByUserId(userId);
            //生成购买库存积分记录
            Integer insert = this.buyStockScore("a", accountShopDTO.getUserId(), 4, cash, new BigDecimal(0),
                    new BigDecimal(0), new BigDecimal(0), new BigDecimal(0), cash.divide(new BigDecimal(Integer.parseInt(buyStockScore.getFieldValue())), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10000)), "商家下单申请积分", json);
            //现金余额
            json.put("cash", accountShopDTO.getCash());
            //华宝余额
            json.put("kaiyuan", accountShopDTO.getKaiyuan());
            //华宝货款余额
            json.put("kaiyuanTurnover", accountShopDTO.getKaiyuanTurnover());
            //查询华宝支付手续费
            SktSysConfigs kaiyuanFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");
            accountShopDTO.setKaiyuanFee(new BigDecimal(kaiyuanFee.getFieldValue()).divide(new BigDecimal(100)).multiply(cash));
            //综合服务费
            SktSysConfigs taxRatio = sysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");
            //传入json华宝支付服务费
            json.put("hbFee", new BigDecimal(taxRatio.getFieldValue()).add(new BigDecimal(kaiyuanFee.getFieldValue())).divide(new BigDecimal(100)).multiply(cash));//华宝支付所需总费用
            //华宝货款手续费
            SktSysConfigs kaiyuanturnFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
            //华宝货款支付所需服务费
            json.put("huabaoturnFee", new BigDecimal(kaiyuanturnFee.getFieldValue()).divide(new BigDecimal(100)).multiply(cash));
            /**
             * 支付方式 1:线下现金支付 2 现金账户支付
             * 3开元宝支付 4第三方支付 5混合支付 6开元宝营业额
             */
            if (insert == 1) {
                json.put("allowPayType", "2,3,4,6");
                json.put("code", "01");
                json.put("msg", "下单成功！");
            } else {
                json.put("code", "00");
                json.put("msg", "购买库存积分失败！");
            }
            return json;
        }
        json.put("code", "00");
        json.put("msg", "购买库存积分请在" + beginTime.getFieldValue() + "点到" + endTime.getFieldValue() + "点之间！");
        return json;
    }

    //用户充值生成订单
    @Override
    public JSONObject recharge(Integer userId, Integer payType, BigDecimal cash, String remark, Integer status) {
        JSONObject json = new JSONObject();
        //用户充值记录
        UsersRecharge recharge = new UsersRecharge();
        // 生成订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        recharge.setOrderNo("7" + strDate + num);
        recharge.setUserId(userId);
        recharge.setPayType(payType);
        recharge.setCash(cash);
        recharge.setRemark(remark);
        recharge.setStatus(status);
        recharge.setCreateTime(new Date());
        Integer insert = usersRechargeMapper.insert(recharge);
        json.put("code", "01");
        /**
         * 支付方式 1:线下现金支付 2 现金账户支付
         * 3开元宝支付 4第三方支付 5混合支付 6开元宝营业额
         */

		json.put("orderNO", recharge.getOrderNo());
		json.put("cash", cash);
		json.put("type", "RECHARGE");
        json.put("allowPayType", "1,4");
        json.put("id", recharge.getId());
        json.put("msg", "下单成功！");
        return json;
    }

    @Transactional
    //购买库存成功，添加库存扣除相应类型的金额
    @Override
    public JSONObject buyStockScoreAfter(SktOrdersStockscore sktOrdersStockscore, String payPwd) {
		JSONObject json = new JSONObject();
		try {
			int payTypes = sktOrdersStockscore.getPayType();
			if (payTypes==3 || payTypes==6 || payTypes==2 ){
				json.put("code", "00");
				json.put("msg", "无法购买");
				return json;
			}
			JSONObject jsonObject = usersService.checkPayPassWorld(sktOrdersStockscore.getUserId(), payPwd);
			if ("00".equals(jsonObject.get("code").toString())) {
				return jsonObject;
			} else {

				//查询订单信息
				SktOrdersStockscore sktOrdersStockscore2 = sktOrdersStockscoreMapper.selectById(sktOrdersStockscore.getOrderId());
				AccountShopDTO accountShopDTO = accountShopMapper.findAccountByUserId(sktOrdersStockscore.getUserId());
				Account account = am.findScoreById(accountShopDTO.getUserId());
				String orderNo=sktOrdersStockscore2.getOrderNo();
				Integer userId=	sktOrdersStockscore2.getUserId();
				Users users = usersService.selectById(userId);
				Integer userType=users.getUserType();
				BigDecimal totalMoney = sktOrdersStockscore2.getTotalMoney();
				if (userType==0){
					insertLogScoreFreeze(0,3,orderNo,account.getScore(),"购买库存积分获得",totalMoney.multiply(new BigDecimal(100)),1,userId);
					account.setFreezeScore(account.getFreezeScore().add(totalMoney.multiply(new BigDecimal(100))));
				}else {
					insertLogScore(0,3,orderNo,account.getScore(),"购买库存积分获得",totalMoney.multiply(new BigDecimal(100)),1,userId);
					account.setScore(account.getScore().add(totalMoney.multiply(new BigDecimal(100))));
					account.setTotalScore(account.getTotalScore().add(totalMoney.multiply(new BigDecimal(100))));
				}

				//判断payType类型   1:线下现金支付 2 现金账户支付 3开元宝支付 4第三方支付 5混合支付 6开元宝营业额
				if (sktOrdersStockscore.getPayType() == 1) {
					//线下现金支付
					//更改订单状态
					//this.updateOrderStockScore(Integer orderStatus,Integer payType,);
				} else if (sktOrdersStockscore.getPayType() == 2) {
					BigDecimal cash1 = account.getCash();
					BigDecimal cash2 = sktOrdersStockscore.getCash();
					if (cash2.compareTo(cash1)==1){
						json.put("code", "00");
						json.put("msg", "现金账户余额不足以支付本次购买");
						return json;
					}
					//现金账户支付Integer userId, Integer orderStatus, Integer payType, BigDecimal cash, BigDecimal kaiyuan, BigDecimal realMoney, BigDecimal kaiyuanFree
					this.updateOrderStockScore(sktOrdersStockscore.getUserId(), 3, 2, sktOrdersStockscore.getCash(), null, null, null);

					//sktOrdersStockscore = sktOrdersStockscoreMapper.selectById(sktOrdersStockscore);
					//扣除相应金额
					this.insertLogCash(-1, accountShopDTO.getUserId(), accountShopDTO.getUserId(), sktOrdersStockscore2.getOrderNo(), account.getCash(), "商家现金余额申请积分", 32, sktOrdersStockscore.getCash());
					BigDecimal cash = sktOrdersStockscore.getCash();
					account.setCash(account.getCash().subtract(cash));


					am.updateById(account);
				} else if (sktOrdersStockscore.getPayType() == 3) {
					BigDecimal huabao1=account.getKaiyuan();
					BigDecimal huabao2=	sktOrdersStockscore.getKaiyuan().add(sktOrdersStockscore.getKaiyuanFee());
				if (huabao2.compareTo(huabao1)==1){
					json.put("code", "00");
					json.put("msg", "华宝账户余额不足以支付本次购买");
					return json;
				}
						//开元宝支付
					this.updateOrderStockScore(sktOrdersStockscore.getUserId(), 3, 3, null, sktOrdersStockscore.getKaiyuan(), null, sktOrdersStockscore.getKaiyuanFee());
					//扣除相应金额
					this.insertLogKaiyuan(account.getUserId(), sktOrdersStockscore.getKaiyuan(), -1,sktOrdersStockscore2.getOrderNo() , account.getKaiyuan(), "商家华宝申请积分", 35, account.getUserId());
					this.insertLogKaiyuan(account.getUserId(), sktOrdersStockscore.getKaiyuanFee(), -1, sktOrdersStockscore2.getOrderNo(), account.getKaiyuan().subtract(sktOrdersStockscore.getKaiyuan()), "商家华宝申请积分手续费和综合服务费率", 36, account.getUserId());
					account.setKaiyuan(account.getKaiyuan().subtract(sktOrdersStockscore.getKaiyuan().add(sktOrdersStockscore.getKaiyuanFee())));
					am.updateById(account);
				} else if (sktOrdersStockscore.getPayType() == 4) {
					//第三方支付
					BigDecimal realMoney = sktOrdersStockscore.getRealMoney();
					this.updateOrderStockScore(sktOrdersStockscore.getUserId(), 3, 4, null, null, null, realMoney);
				} else if (sktOrdersStockscore.getPayType() == 5) {
					//混合支付
				} else if (sktOrdersStockscore.getPayType() == 6) {
					BigDecimal huabao2=	sktOrdersStockscore.getKaiyuan().add(sktOrdersStockscore.getKaiyuanFee());
					BigDecimal kaiyuanTurnover = accountShopDTO.getKaiyuanTurnover();
					if (huabao2.compareTo(kaiyuanTurnover)==1){
						json.put("code", "00");
						json.put("msg", "华宝货款账户余额不足以支付本次购买");
						return json;
					}
					//开元宝营业额
					this.updateOrderStockScore(sktOrdersStockscore.getUserId(), 3, 6, null, sktOrdersStockscore.getKaiyuan(), null, sktOrdersStockscore.getKaiyuanFee());
					//扣除相应金额
					this.insertLogKaiYuanTurnover(35,0,account.getUserId(),sktOrdersStockscore2.getOrderNo() ,accountShopDTO.getKaiyuanTurnover(), -1, sktOrdersStockscore.getKaiyuan(),  "商家华宝货款申请积分");
					this.insertLogKaiYuanTurnover(36,0,account.getUserId(),sktOrdersStockscore2.getOrderNo(), accountShopDTO.getKaiyuanTurnover().subtract(sktOrdersStockscore.getKaiyuan()), -1,sktOrdersStockscore.getKaiyuanFee(), "商家华宝货款申请积分手续费和综合服务费率");
					accountShopDTO.setKaiyuanTurnover(accountShopDTO.getKaiyuanTurnover().subtract(sktOrdersStockscore.getKaiyuan().add(sktOrdersStockscore.getKaiyuanFee())));
					Map<String,Object> map = new HashMap<>();
					map.put("allmoney",sktOrdersStockscore.getKaiyuan().add(sktOrdersStockscore.getKaiyuanFee()));
					map.put("userId",sktOrdersStockscore.getUserId());
					accountShopMapper.updateKaiyuanTurnoverByUserId(map);
					am.updateById(account);
				}
				//查询用户实时库存
				AccountShop accountShop = accountShopMapper.findShopId(account.getUserId());
				//从订单表中查询购买多少库存积分
				BigDecimal stockScore = sktOrdersStockscoreMapper.findStockScore(sktOrdersStockscore.getOrderId());
				sktOrdersStockscore = sktOrdersStockscore.selectById(sktOrdersStockscore.getOrderId());
				//生成库存记录表
				this.insertLogStockScore(1, account.getUserId(), account.getUserId(), orderNo, accountShop.getStockScore(), 1, stockScore, "商家购买库存积分");
				//添加库存积分
				accountShop.setStockScore(accountShop.getStockScore().add(stockScore));
				accountShop.setTotalStockScore(accountShop.getTotalStockScore().add(stockScore));
				Integer update = accountShopMapper.updateStockScoreById(accountShop);
				if (update == 1) {
					json.put("code", "01");
					json.put("msg", "申请成功");
				} else {
					json.put("code", "00");
					json.put("msg", "申请失败");
				}
				return json;
			}

		}catch (Exception e){
    		e.printStackTrace();
			json.put("code", "00");
			json.put("msg", "申请失败");
			return json;
		}
    }

	/**
	 * 用户消费下单 web
	 * @param orderIdList  订单集合
	 * @return
	 */
	@Transactional
	@Override

	public Map<String,Object> userSale( List<String> orderIdList,Integer payType,BigDecimal payMoney,BigDecimal feeMoney,Integer userId){
		Map<String,Object> map=new HashMap<String,Object>();
		// TODO Auto-generated method stub
		try {
			if(orderIdList!=null && orderIdList.size()>0){
				BigDecimal totalM=BigDecimal.ZERO;
				for (String orderId:orderIdList){
					SktOrders sktOrders = ordersMapper.selectById(orderId);
					if (sktOrders.getOrderStatus()==-1){
						map.put("code","00");
						map.put("msg","订单已过期");
						return map;
					}
					totalM=totalM.add(sktOrders.getTotalMoney());
				}
				BigDecimal changeKaiYuanM=totalM.multiply(new BigDecimal(100));
				SktSysConfigs taxRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");//综合服务费%
				String  taxRatios=taxRatio.getFieldValue();//综合服务费用
				BigDecimal ratio=new BigDecimal(taxRatios);
				SktSysConfigs kaiyuanFees = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");//华宝支付手续费%
				String  kaiyuanFee=kaiyuanFees.getFieldValue();//华宝服务费用
				BigDecimal kaiyuanF=new BigDecimal(kaiyuanFee);
				BigDecimal kaiyuanFe=(kaiyuanF.add(ratio)).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
				SktSysConfigs kaiyuanturnFee = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
				String  kaiyuanturnFe=kaiyuanturnFee.getFieldValue();//华宝货款支付手续费%
				BigDecimal kaiyuanturnF=new BigDecimal(kaiyuanturnFe);
				BigDecimal kaiyuanturnFef=kaiyuanF.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);

				BigDecimal kaiyuanturnFees=changeKaiYuanM.add(changeKaiYuanM.multiply(kaiyuanturnFef));
                Account account=am.selectAccountByuserId(userId);
                BigDecimal userCash=account.getCash();
				BigDecimal userKaiyuan=account.getKaiyuan();
                BigDecimal total=payMoney.add(feeMoney);
                if (payType==2 && totalM.compareTo(userCash)==1){
                	map.put("code","00");
					map.put("msg","账户现金余额不足");
					return map;
				}
				BigDecimal totalF=totalM.multiply(new BigDecimal(100));
				BigDecimal totalKYSXF = totalF.multiply(kaiyuanFe);
				BigDecimal zongKY=totalF.add(totalKYSXF);
				if(payType==3 && zongKY.compareTo(userKaiyuan)==1){
					map.put("code","00");
					map.put("msg","账户华宝余额不足");
					return map;
				}
				if(payType==6){
					BigDecimal totalFT=totalM.multiply(new BigDecimal(100));
				//	BigDecimal totalKYHLSXF =totalFT.multiply(kaiyuanturnFees);
				//	BigDecimal zongKYHK=totalFT.add(totalKYHLSXF);
					AccountShop   userAccountShop=new AccountShop();
					userAccountShop.setUserId(userId);
					EntityWrapper<AccountShop> entityWrapper=new EntityWrapper<AccountShop>(userAccountShop) ;
					AccountShop userAccountShop1 = accountShopService.selectOne(entityWrapper);
					BigDecimal kaiyuanTurnover = userAccountShop1.getKaiyuanTurnover();
					if(kaiyuanturnFees.compareTo(kaiyuanTurnover)==1){
						map.put("code","00");
						map.put("msg","账户华货款宝余额不足");
						return map;
					}
				}
                BigDecimal cash =BigDecimal.ZERO;
                BigDecimal kaiyuan=BigDecimal.ZERO;
             //   BigDecimal bigSumScore=BigDecimal.ZERO;
			//	BigDecimal sumMoney =BigDecimal.ZERO;
				BigDecimal changeKaiYuan=BigDecimal.ZERO;
				int sumPayScore=0;
				for (String orderId:orderIdList){
					SktOrders sktOrders = ordersMapper.selectById(orderId);
					sumPayScore=sumPayScore+sktOrders.getPayScore();
				}
				BigDecimal BigPayScore=new BigDecimal(sumPayScore);
				if(BigPayScore.compareTo(account.getScore())==1){
					map.put("code","00");
					map.put("msg","你的积分不足以扣除自营店商品");
					return map;
				}
				int payScore=0;
				for (String orderId:orderIdList){
                //    userId = ordersMapper.selectById(orderIdList.get(0)).getUserId();
					SktOrders sktOrders = ordersMapper.selectById(orderId);
					SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String paymentTimes = sdft.format(new Date());
					Date paymentTime=sdft.parse(paymentTimes);
                    cash = account.getCash();
                    kaiyuan = account.getKaiyuan();
					Integer shopId = sktOrders.getShopId();
					SktShops sktShops = sktShopsService.selectById(shopId);
					Map<String,Object> map2 = new HashMap<String,Object>();
					if(sktShops.getCompanyType() == 0) {
						//个体户每日限额
						SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("gthMRXE");
						String gthMRXE = sktSysConfigs2.getFieldValue();
						Map<String,Object> map3 = new HashMap<String,Object>();
						map3.put("shopId",shopId);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String today = sdf.format(new Date());
						map3.put("today",today);
						//查询商家的今日营业额
						BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map3);
						if(todayTurnover != null){
							if(todayTurnover.add(sktOrders.getGoodsMoney()).compareTo(new BigDecimal(gthMRXE)) == 1){
								map2.put("msg","对不起商家"+sktShops.getShopName()+"今日销售限额已达上限！");
								return map2;
							}
						}
					}
					if(sktShops.getCompanyType() == 1){
						//公司每日限额
						SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("qyMRXE");
						String qyMRXE = sktSysConfigs2.getFieldValue();
						Map<String,Object> map3 = new HashMap<String,Object>();
						map3.put("shopId",shopId);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String today = sdf.format(new Date());
						map3.put("today",today);
						//查询商家的今日营业额
						BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map3);
						if(todayTurnover != null){
							if(todayTurnover.add(sktOrders.getGoodsMoney()).compareTo(new BigDecimal(qyMRXE)) == 1){
								map2.put("msg","对不起商家"+sktShops.getShopName()+"今日销售限额已达上限！");
								return map2;
							}
						}
					}
					Integer notPayCountShop = sktOrdersStoresMapper.appFindNotPayOrders(map2);
					if(notPayCountShop!=null){
						if(notPayCountShop >= 2){
							map2.put("msg","对不起，您今日在本店铺未支付订单已达上线（2单），不能在此店铺下单了！");
							return map2;
						}
					}

					//查询用户今天所有未支付订单
					map2.put("shopId","");
					Integer notPayCountAll = sktOrdersStoresMapper.appFindNotPayOrders(map2);
					if(notPayCountAll!=null){
						if(notPayCountShop >= 5){
							map2.put("msg","对不起，您今日未支付订单已达上线（5单），不能再下单了！");
							return map2;
						}
					}
					AccountShop accountShop = accountShopMapper.selectByShopId(shopId);
					List<SktOrderGoods> list = ordersMapper.getOrderGoodsByOrderId(Integer.parseInt(orderId));
					SktOrdersExtension ordersExtension=new SktOrdersExtension();//订单扩展表
					ordersExtension.setOrderId(sktOrders.getOrderId().toString());//订单扩展表
					Map<String, Object> afterSevenWorkDay = getAfterSevenWorkDay(7);
					//String  StrAutoTakeTime=afterSevenWorkDay.get("endDay").toString();
					String  endDays=afterSevenWorkDay.get("endDay").toString().substring(0,10);
					SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
					String time = format.format(new Date());
					String  newTime=endDays+" "+time;
					SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
					Date newDate  = sdf.parse(newTime );
					ordersExtension.setAutoTakeTime(newDate); //应自动收货时间
					ordersExtension.setIsAutoTake(0);//是否自动收货 0否；1是 2已手动收货
					ordersExtension.setIsSettle(1);//批处理标示符：1未处理 2已处理 9处理中
					BigDecimal sumScore=BigDecimal.ZERO;
					if(payType==2){//现金账户
//                        BigDecimal deliverMoney = sktOrders.getDeliverMoney();
//                        BigDecimal money = sktOrders.getGoodsMoney();
                        BigDecimal tatolMoney=sktOrders.getTotalMoney();
//						sumMoney=sumMoney.add(money);
						for (SktOrderGoods orderGoods:list) {
						//	Integer shopId = goodsMapper.selectById(orderGoods.getGoodsId()).getShopId();
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsStock){
								map.put("code","00");
								map.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  map;
							}
							/**
							 * 查询规格下的物品库存，如果没有规格，用商品总库存
							 */



							/**
							 * 从缓存中获取库存
							 */
//							String redisKey = "redis_key:stock:" +goodsId;
//
//							JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
//
//							if (jsonObject==null){
//								map.put("code","00");
//								map.put("msg","订单已过期");
//								return  map;
//							}
							//	int	goodsStock = jsonObject.getInteger("goodsStock");
//							goods.setGoodsStock(goodsStock-goodsNum);
//							goodsService.updateById(goods);
//							if(jsonObject.getBoolean("isSpec")){
//								String goodsSpecId=orderGoods.getGoodsSpecId();
////								JSONObject spec = jsonObject.getJSONObject("spec");
////								Integer	Stock = spec.getInteger(goodsSpecId);
//
//								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
//								int SpecStock=	goodsSpecs.getSpecStock();
//								if (goodsNum>SpecStock){
//									map.put("code","00");
//									map.put("msg","商品"+goods.getGoodsName()+"库存不足");
//									return  map;
//								}
//								goodsSpecs.setSpecStock(SpecStock-goodsNum);
//								goodsSpecsService.updateById(goodsSpecs);
//							};
						//	cacheUtil.remove(redisKey);
						//	int goodsNum=orderGoods.getGoodsNum();
						//	BigDecimal score=	orderGoodsScore;
							sumScore=sumScore.add(orderGoodsScore);
						}
					//	bigSumScore=bigSumScore.add(sumScore);
						sktOrders.setIsPay(1);
						sktOrders.setPayType(2);
						sktOrders.setOrderStatus(0);
						sktOrders.setCash(tatolMoney);
                        sktOrders.setTotalMoney(tatolMoney);
						sktOrders.setPaymentTime(new Date());
						ordersExtension.setScore(sumScore);//订单扩展表
						if(accountShop.getStockScore().compareTo(sumScore)==1){  //商家库存积分是否充足

							this.insertLogStockScore(2,accountShop.getUserId(),accountShop.getUserId(),sktOrders.getOrderNo(),accountShop.getStockScore(),-1,sumScore,"商城下单冻结库存积分");
							accountShop.setStockScore(accountShop.getStockScore().subtract(sumScore));
							accountShop.setFreezeStockScore(accountShop.getFreezeStockScore().add(sumScore));
							ordersExtension.setScoreFlag(1);//库存积分标识：1店铺库存积分充足 2库存不足扣营业额购买库存积分

						//	account.setCash(account.getCash().subtract(payMoney));

						}else{
							ordersExtension.setScoreFlag(2);//库存积分标识：1店铺库存积分充足 2库存不足扣营业额购买库存积分
                            List<Integer> usersIds=new ArrayList<Integer>();
                            usersIds.add(accountShop.getUserId());
                            messagesService.addMessages(1,1,usersIds,"您的积分不足以赠送当前客户购买的商品，此订单将延迟结算货款，为不影响您的日常交易，请尽快购买库存积分",null);
						}
						//生成现金流水
						this.insertLogCash(-1, 0, userId, sktOrders.getOrderNo(), cash, "线上商城消费", 33,tatolMoney );
						ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
						accountShopMapper.updateAccountShop(accountShop);//商家积分进入冻结
                        account.setCash(account.getCash().subtract(tatolMoney));
                        am.updateAccount(account);//用户账户变化
						ordersMapper.updateById(sktOrders);
					}
					if(payType==3){//华宝支付
						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsStock){
								map.put("code","00");
								map.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  map;
							}
							/**
							 * 查询规格下的物品库存，如果没有规格，用商品总库存
							 */



//							/**
//							 * 从缓存中获取库存
//							 */
//							String redisKey = "redis_key:stock:" +goodsId;
//
//							JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
//							if (jsonObject==null){
//								map.put("code","00");
//								map.put("msg","订单已过期");
//								return  map;
//							}
//							//	int	goodsStock = jsonObject.getInteger("goodsStock");
//							goods.setGoodsStock(goodsStock-goodsNum);
//							goodsService.updateById(goods);
//							if(jsonObject.getBoolean("isSpec")){
//								String goodsSpecId=orderGoods.getGoodsSpecId();
////								JSONObject spec = jsonObject.getJSONObject("spec");
////								Integer	Stock = spec.getInteger(goodsSpecId);
//
//								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
//								int SpecStock=	goodsSpecs.getSpecStock();
//								if (goodsNum>SpecStock){
//									map.put("code","00");
//									map.put("msg","商品"+goods.getGoodsName()+"库存不足");
//									return  map;
//								}
//								goodsSpecs.setSpecStock(SpecStock-goodsNum);
//								goodsSpecsService.updateById(goodsSpecs);
//							};
						//	cacheUtil.remove(redisKey);
						//	int goodsNum=orderGoods.getGoodsNum();
						//	BigDecimal score=	orderGoodsScore.multiply(new BigDecimal(goodsNum));
							sumScore=sumScore.add(orderGoodsScore);
						}
//                        BigDecimal deliverMoney = sktOrders.getDeliverMoney();
//                        BigDecimal money = sktOrders.getGoodsMoney();
//                        BigDecimal tatolMoney=money.add(deliverMoney);
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
						changeKaiYuan=tatolMoney.multiply(new BigDecimal(100));
//                        SktSysConfigs taxRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");//综合服务费%
//                        String  taxRatios=taxRatio.getFieldValue();//综合服务费用
//                        BigDecimal ratio=new BigDecimal(taxRatios);
//                        SktSysConfigs kaiyuanFees = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");//华宝支付手续费%
//                        String  kaiyuanFee=kaiyuanFees.getFieldValue();//综合服务费用
//                        BigDecimal kaiyuanF=new BigDecimal(kaiyuanFee);
//                        BigDecimal kaiyuanFe=kaiyuanF.add(ratio).divide(new BigDecimal(100),2);

                    //    BigDecimal totalKaiYuan=changeKaiYuan.add(changeKaiYuan.multiply(kaiyuanFe));
						if(accountShop.getStockScore().compareTo(sumScore)==1){
							this.insertLogStockScore(2,accountShop.getUserId(),accountShop.getUserId(),sktOrders.getOrderNo(),accountShop.getStockScore(),-1,sumScore,"商城下单冻结库存积分");
							accountShop.setStockScore(accountShop.getStockScore().subtract(sumScore));
							accountShop.setFreezeStockScore(accountShop.getFreezeStockScore().add(sumScore));
							ordersExtension.setScoreFlag(1);

						//	account.setKaiyuan(kaiyuan.subtract(changeKaiYuan));
						}else{
							ordersExtension.setScoreFlag(2);
						}
						// 华宝消费记录
						this.insertLogKaiyuan(0, changeKaiYuan, -1, sktOrders.getOrderNo(), account.getKaiyuan(), "线上商城消费支出", 31, account.getUserId());
						//华宝消费手续费记录
						this.insertLogKaiyuan(0, changeKaiYuan.multiply(kaiyuanFe), -1, sktOrders.getOrderNo(), account.getKaiyuan().subtract(changeKaiYuan), "消费的手续费和税率的支出", 32, account.getUserId());
						sktOrders.setIsPay(1);
						sktOrders.setPayType(3);
						sktOrders.setKaiyuan(changeKaiYuan);
						sktOrders.setKaiyuanFee(changeKaiYuan.multiply(kaiyuanFe));
                        sktOrders.setTotalMoney(tatolMoney);
                        sktOrders.setOrderStatus(0);
						sktOrders.setPaymentTime(new Date());
                        ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
						accountShopMapper.updateAccountShop(accountShop);//商家积分进入冻结
						BigDecimal	toal=changeKaiYuan.add(changeKaiYuan.multiply(kaiyuanFe));
                        account.setKaiyuan(account.getKaiyuan().subtract(toal));
                        am.updateAccount(account);//用户账户变化
						ordersMapper.updateById(sktOrders);
					}
                    if(payType==6){
                        for (SktOrderGoods orderGoods:list) {
                            BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsStock){
								map.put("code","00");
								map.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  map;
							}
							/**
							 * 查询规格下的物品库存，如果没有规格，用商品总库存
							 */



							/**
							 * 从缓存中获取库存
							 */
//							String redisKey = "redis_key:stock:" +goodsId;
//
//							JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
//							if (jsonObject==null){
//								map.put("code","00");
//								map.put("msg","订单已过期");
//								return  map;
//							}
//							//	int	goodsStock = jsonObject.getInteger("goodsStock");
//							goods.setGoodsStock(goodsStock-goodsNum);
//							goodsService.updateById(goods);
//							if(jsonObject.getBoolean("isSpec")){
//								String goodsSpecId=orderGoods.getGoodsSpecId();
////								JSONObject spec = jsonObject.getJSONObject("spec");
////								Integer	Stock = spec.getInteger(goodsSpecId);
//
//								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
//								int SpecStock=	goodsSpecs.getSpecStock();
//								if (goodsNum>SpecStock){
//									map.put("code","00");
//									map.put("msg","商品"+goods.getGoodsName()+"库存不足");
//									return  map;
//								}
//								goodsSpecs.setSpecStock(SpecStock-goodsNum);
//								goodsSpecsService.updateById(goodsSpecs);
//							};
						//	cacheUtil.remove(redisKey);
                         //   int goodsNum=orderGoods.getGoodsNum();
                            //	BigDecimal score=	orderGoodsScore.multiply(new BigDecimal(goodsNum));
                            sumScore=sumScore.add(orderGoodsScore);
                        }
//                        BigDecimal deliverMoney = sktOrders.getDeliverMoney();
//                        BigDecimal money = sktOrders.getGoodsMoney();
//                        BigDecimal tatolMoney=money.add(deliverMoney);
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
                        changeKaiYuan=tatolMoney.multiply(new BigDecimal(100));
//                        SktSysConfigs taxRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");//综合服务费%
//                        String  taxRatios=taxRatio.getFieldValue();//综合服务费用
//                        BigDecimal ratio=new BigDecimal(taxRatios);
//                        SktSysConfigs kaiyuanturnFee = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
//                        String  kaiyuanturnFe=kaiyuanturnFee.getFieldValue();//华宝货款支付手续费%
//                        BigDecimal kaiyuanturnF=new BigDecimal(kaiyuanturnFe);
//                        BigDecimal kaiyuanturnFef=kaiyuanF.add(ratio).divide(new BigDecimal(100),2);
                        AccountShop   userAccountShop=new AccountShop();
						userAccountShop.setUserId(userId);
                        EntityWrapper<AccountShop> entityWrapper=new EntityWrapper<AccountShop>(userAccountShop) ;
                        AccountShop userAccountShop1 = accountShopService.selectOne(entityWrapper);
                        BigDecimal  tatolKaiyuanTurnover=changeKaiYuan.add(changeKaiYuan.multiply(kaiyuanturnFef));
                        if(accountShop.getStockScore().compareTo(sumScore)==1){
                            this.insertLogStockScore(2,accountShop.getUserId(),accountShop.getUserId(),sktOrders.getOrderNo(),accountShop.getStockScore(),-1,sumScore,"商城下单冻结库存积分");
                            accountShop.setStockScore(accountShop.getStockScore().subtract(sumScore));
                            accountShop.setFreezeStockScore(accountShop.getFreezeStockScore().add(sumScore));
                            ordersExtension.setScoreFlag(1);
                             }else{
                            ordersExtension.setScoreFlag(2);
                        }
                        if(userAccountShop1!=null){
                            userAccountShop1.setKaiyuanTurnover(userAccountShop1.getKaiyuanTurnover().subtract(tatolKaiyuanTurnover));
                            accountShopService.updateById(userAccountShop1);
                        }
						// 华宝货款消费记录
						this.insertLogKaiYuanTurnover(31,0,userId,sktOrders.getOrderNo(),userAccountShop1.getKaiyuanTurnover(),-1,changeKaiYuan,"线上商城消费支出");
						this.insertLogKaiYuanTurnover(32,0,userId,sktOrders.getOrderNo(),userAccountShop1.getKaiyuanTurnover().subtract(changeKaiYuan.multiply(kaiyuanturnFef)),-1,changeKaiYuan.multiply(kaiyuanturnFef),"消费的手续费和税率的支出");

						sktOrders.setIsPay(1);
                        sktOrders.setPayType(3);
                        sktOrders.setKaiyuan(changeKaiYuan);
                        sktOrders.setKaiyuanFee(changeKaiYuan.multiply(kaiyuanturnFef));
                        sktOrders.setTotalMoney(tatolMoney);
                        sktOrders.setOrderStatus(0);
						sktOrders.setPaymentTime(new Date());
                        ordersExtension.setScore(sumScore);
                        SktOrdersExtensionMapper.insert(ordersExtension);
                        accountShopMapper.updateAccountShop(accountShop);//商家积分进入冻结
						ordersMapper.updateById(sktOrders);
                    }
					if(payType==4){//者第三方
						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsNum=orderGoods.getGoodsNum();
						//	BigDecimal score=	orderGoodsScore.multiply(new BigDecimal(goodsNum));
							sumScore=sumScore.add(orderGoodsScore);
						}
						if(accountShop.getStockScore().compareTo(sumScore)==1){
							this.insertLogStockScore(2,accountShop.getUserId(),accountShop.getUserId(),sktOrders.getOrderNo(),accountShop.getStockScore(),-1,sumScore,"商城下单冻结库存积分");
							accountShop.setStockScore(accountShop.getStockScore().subtract(sumScore));
							accountShop.setFreezeStockScore(accountShop.getFreezeStockScore().add(sumScore));
							ordersExtension.setScoreFlag(1);
						}else{
							ordersExtension.setScoreFlag(2);
						}
                        BigDecimal money = sktOrders.getTotalMoney();
						sktOrders.setIsPay(1);
						sktOrders.setPayType(4);
						sktOrders.setRealMoney(money);
                        sktOrders.setOrderStatus(0);
						sktOrders.setPaymentTime(new Date());
                        SktOrdersExtensionMapper.insert(ordersExtension);
						accountShopMapper.updateAccountShop(accountShop);//商家积分进入冻结
						ordersMapper.updateById(sktOrders);
					}
					if(sktOrders.getPayScore()>0){
						payScore=sktOrders.getPayScore();
					}
					if(payScore>0){
						insertLogScore(0,33,sktOrders.getOrderNo(),account.getScore(),"购买自营商品",new BigDecimal(payScore),-1,userId);
						account.setScore(account.getScore().subtract(new BigDecimal(payScore)));
						am.updateById(account);
					}
                    List<Integer> usersIds=new ArrayList<Integer>();
                    usersIds.add(accountShop.getUserId());
                    //发送系统消息
                    messagesService.addMessages(1,1,usersIds,"您有一笔订单【"+sktOrders.getOrderNo()+"】用户已支付，请尽快发货",null);

					//生成订单记录表
                    this.insertLogOrders(sktOrders.getOrderId(),-2,"下单成功，等待用户支付",userId,0);
                }
			//	map.put("createTime",new);
				map.put("totalMoney",totalM);
				map.put("code","01");
			}
			return map;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","出异常了");
			return map;
		}
	}

	/**
	 * 线上用户确认收货
	 * @param orderIdList  订单id集合
	 * @return
	 */
	@Transactional
	@Override
	 public boolean toPayGoods(List<Integer> orderIdList) {
		// TODO Auto-generated method stub
        try{
        	if(orderIdList!=null && orderIdList.size()>0){
				int userId=0;
				BigDecimal sumScore=new BigDecimal("0");//买家用户获得积分
				BigDecimal sumCash=new BigDecimal("0");//买家用户消费金额
				for (Integer orderId:orderIdList){
					userId = ordersMapper.selectById(orderIdList.get(0)).getUserId();
					SktOrders orders = ordersMapper.selectById(orderId);
					BigDecimal cash=orders.getGoodsMoney();
					sumCash=sumCash.add(cash);
					BigDecimal kaiyuan=orders.getKaiyuan();
					int shopId=orders.getShopId();
					int payScore = orders.getPayScore();
					if(payScore>0){
				//如果payScore大于0，则累加到skt_account_system表中
						SktAccountSystem sktAccountSystem =new SktAccountSystem();
						sktAccountSystem.setCode("SelfShopScore");
						EntityWrapper<SktAccountSystem> ewap=new EntityWrapper<SktAccountSystem>(sktAccountSystem);
						SktAccountSystem sktAccountSystem1 = sktAccountSystemService.selectOne(ewap);
						sktAccountSystem1.setValue(sktAccountSystem1.getValue().add(new BigDecimal(payScore)));
						sktAccountSystemService.updateById(sktAccountSystem1);
					}
					AccountShop accountShop = accountShopMapper.selectByShopId(shopId);
					Account account=new Account();
					account.setShopId(shopId);
					EntityWrapper<Account> ewp=new EntityWrapper<Account>(account);
					Account account1 = this.selectOne(ewp);//商家对应的个人账户
					BigDecimal score=new BigDecimal("0");//订单获得积分
					List<SktOrderGoods> list = ordersMapper.getOrderGoodsByOrderId(orderId);
					if(list!=null&& list.size()>0){
						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsNum=orderGoods.getGoodsNum();
//							BigDecimal a=	orderGoodsScore.multiply(new BigDecimal(goodsNum));
							score=score.add(orderGoodsScore);
							Goods goods = goodsMapper.selectById(orderGoods.getGoodsId());
							goods.setSaleNum(goods.getSaleNum()+goodsNum);//商品销量增加
							goodsMapper.updateById(goods);
							//商品规格表销售量增加
							GoodsSpecs goodsSpecs=new GoodsSpecs();
							goodsSpecs.setGoodsId(orderGoods.getGoodsId());
							EntityWrapper<GoodsSpecs> ew=new EntityWrapper<GoodsSpecs>(goodsSpecs);
							GoodsSpecs goodsSpecs1 = goodsSpecsService.selectOne(ew);
							if(goodsSpecs1!=null){
								goodsSpecs1.setSaleNum(goodsSpecs1.getSaleNum()+goodsNum);
								goodsSpecsService.updateById(goodsSpecs1);
							}
						}
						sumScore=sumScore.add(score);
					}

					SktOrdersExtension ordersExtension=new SktOrdersExtension();
					ordersExtension.setOrderId(orderId.toString());
					EntityWrapper<SktOrdersExtension> ew=new EntityWrapper<SktOrdersExtension>(ordersExtension);
					SktOrdersExtension sktOrdersExtension = sktOrdersExtensionService.selectOne(ew);
					Integer userSarketId=accountShop.getUserId();
					Users userSarket = usersMapper.selectById(userSarketId);//获得商家对应的user
					int userType=userSarket.getUserType();//得判断商家对应用户类型
					if(sktOrdersExtension.getScoreFlag()==1){ //下单时库存积分充足
						//3.商家账户变更 现金，冻结积分  华宝
						if(cash.compareTo(BigDecimal.ZERO)==1){
							accountShop.setOnlineTurnover(accountShop.getOnlineTurnover().add(cash));//线上商城营业额
						}
						accountShop.setFreezeStockScore(accountShop.getFreezeStockScore().subtract(score));//减少冻结积分
						if(orders.getPayType()==2 ||orders.getPayType()==4){
							if(userType==0){
								freezeCashToFormal(2,0,userSarketId,orders.getOrderNo(),account1.getFreezeCash(),1,orders.getTotalMoney(),"线上商城营业额进入待发");
								account1.setFreezeCash(account1.getFreezeCash().add(orders.getCash()));
							}else{
								insertLogCash(1,0,userSarketId,orders.getOrderNo(),account1.getCash(),"订单结算增加金额",3,orders.getTotalMoney());
								account1.setCash(account1.getCash().add(orders.getTotalMoney()));
								account1.setTotalCash(account1.getTotalCash().add(orders.getCash()));
							}
							accountShop.setTotalGiveStockScore(accountShop.getTotalGiveStockScore().add(score));//累计分发库存积分
							accountShopMapper.updateById(accountShop);
							am.updateById(account1);
						}else if(orders.getPayType()==3){
							if(userType==0){
								//5.商家待发华宝货款
								this.insertLogKaiyuanFreeze(0,kaiyuan,1,orders.getOrderNo(),accountShop.getFreezeKaiyuan(),"线上营业额获得",1,userSarketId);
								accountShop.setFreezeKaiyuan(accountShop.getFreezeKaiyuan().add(kaiyuan));
							}else{
								//6.商家华宝货款流水
								this.hbTurnover(1, 0, userSarketId, orders.getOrderNo(), 1, kaiyuan, "线上营业额获得");
								accountShop.setKaiyuanTurnover(accountShop.getKaiyuanTurnover().add(kaiyuan));//门店获得开元宝支付的营业额
								accountShop.setTotalKaiyuanTurnover(accountShop.getTotalKaiyuanTurnover().add(kaiyuan));//门店累计获得开元宝支付的营业额
							}
							accountShop.setTotalGiveStockScore(accountShop.getTotalGiveStockScore().add(score));//累计分发库存积分
							accountShopMapper.updateById(accountShop);
						}else if (orders.getPayType()==6){
							if (userType==0){
								this.insertLogKaiyuanFreeze(0,kaiyuan,1,orders.getOrderNo(),accountShop.getFreezeKaiyuan(),"线上营业额获得",1,userSarketId);
								accountShop.setFreezeKaiyuan(accountShop.getFreezeKaiyuan().add(kaiyuan));
							}else{
								this.insertLogKaiYuanTurnover(1,0,userSarketId,orders.getOrderNo(),accountShop.getKaiyuanTurnover(),1,orders.getKaiyuan(),"线上商城营业额获得");
								accountShop.setKaiyuanTurnover(accountShop.getKaiyuanTurnover().add(orders.getKaiyuan()));
								accountShop.setTotalKaiyuanTurnover(accountShop.getTotalKaiyuanTurnover().add(orders.getKaiyuan()));
							}
							accountShop.setTotalGiveStockScore(accountShop.getTotalGiveStockScore().add(score));//累计分发库存积分
							accountShopMapper.updateById(accountShop);
						}

						sktOrdersExtension.setIsAutoTake(2);
						sktOrdersExtension.setSettleTime(new Date());
						sktOrdersExtension.setIsSettle(2);
						sktOrdersExtension.setRealSettleTime(new Date());
						//是否开启销售奖
						sktOrdersExtensionService.updateById(sktOrdersExtension);
						SktSysConfigs sysConfigsisXiaoshou = sysConfigsMapper.selectSysConfigsByFieldCode("isXiaoshou");
						String isXiaoshouValue = sysConfigsisXiaoshou.getFieldValue();
						if("1".equals(isXiaoshouValue)){
							//8卖家推荐人销售奖
							if(userSarket.getInviteId()!=0){
								this.marketAward(userSarket.getInviteId(),score, userId,orders.getOrderNo());
							}
						}
						sktOrdersExtensionService.updateById(sktOrdersExtension);
						SktSysConfigs sysConfigsisOrNoFenrun = sysConfigsMapper.selectSysConfigsByFieldCode("isOrNoFenrun");
						String isOrNoFenrun = sysConfigsisOrNoFenrun.getFieldValue();
						if ("1".equals(isOrNoFenrun)){
							//9.2销售特别奖
							Integer inviteId = userSarket.getInviteId();
							List<Integer> idss = usersService.getIds(userSarket.getUserId());
							if(idss!=null && idss.size()>0){
								SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("turnoverProfit");
								String fieldValue = sysConfig.getFieldValue();
								BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
								specialAward(idss,percent, score,1,inviteId,orders.getOrderNo());
							}
						}

						sktOrdersExtension.setRealSettleTime(new Date());
						sktOrdersExtensionService.updateById(sktOrdersExtension);
						Account account2=am.selectAccountByuserId(userId);
						//1.买家积分流水
						this.insertLogScore(0,1,orders.getOrderNo(), account2.getScore(), "商城消费获取", sumScore, 1, userId);
						//2.买家账户表修改
						account2.setOnlineExpenditure(account2.getOnlineExpenditure().add(sumCash));
						account2.setScore(account2.getScore().add(sumScore));
						account2.setTotalScore(account2.getTotalScore().add(sumScore));
						am.updateById(account2);
						//是否开启销费奖
						SktSysConfigs sysConfigsisXiaofei = sysConfigsMapper.selectSysConfigsByFieldCode("isXiaofei");
						String isXiaofeiValue = sysConfigsisXiaofei.getFieldValue();
						Users userSale = usersMapper.selectById(userId);//获得买家对应的user
						if("1".equals(isXiaofeiValue)){
							//7.买家推荐人消费奖励

							if(userSale.getInviteId()!=0){
								this.saleAward(userSale.getInviteId(), sumScore,userId,orders.getOrderNo());
							}
						}

						if ("1".equals(isOrNoFenrun)){
							//9.特别奖励
							//9.1 消费特别奖
							List<Integer> ids = usersService.getIds(userId);
							if(ids!=null && ids.size()>0){
								SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("consumeProfit");
								String fieldValue = sysConfig.getFieldValue();
								BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
								specialAward(ids,percent, sumScore,1,userSale.getInviteId(),orders.getOrderNo());
							}
						}

					}else if(sktOrdersExtension.getScoreFlag()==2){//下单时库存积分不足
						SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScorePrice");
						String fieldValue = sysConfig.getFieldValue();
						BigDecimal buyStockScorePrice=new BigDecimal(fieldValue).divide(new BigDecimal(10000));
						BigDecimal subCash=score.multiply(buyStockScorePrice);
						cash=	cash.subtract(subCash);
						if(orders.getPayType()==2||orders.getPayType()==4){
							if(userType==0){
								freezeCashToFormal(-1,0,userSarket.getUserId(),orders.getOrderNo(),account1.getFreezeCash(),32,subCash,"店铺积分不足支付订单购买库存积分扣除现金");
							}else {
								insertLogCash(-1, 0, userSarket.getUserId(), orders.getOrderNo(), account1.getCash(), "店铺积分不足支付订单购买库存积分扣除现金", 32, subCash);
							}
							insertStockScore(orders.getOrderNo(), userSarket.getUserId(), 2, cash, BigDecimal.ZERO, cash, new BigDecimal(0), new BigDecimal(0), score, "库存积分不足订单结算系统自动购买");
							this.insertLogStockScore(1,0,userSarket.getUserId(),orders.getOrderNo(),accountShop.getStockScore(),-1,score,"库存积分不足订单结算系统自动购买");

						}else if (orders.getPayType()==3||orders.getPayType()==6){
							SktSysConfigs sysConfigs = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
							String fieldValues = sysConfig.getFieldValue();
							BigDecimal kaiyuanturnFee=new BigDecimal(fieldValue).divide(new BigDecimal(100));
							BigDecimal payKaiYuan = kaiyuan.multiply(buyStockScorePrice).multiply(new BigDecimal(100));
							BigDecimal feeKaiYuan = payKaiYuan.multiply(kaiyuanturnFee);
							if(userType==0){
								this.insertLogKaiyuanFreeze(0,payKaiYuan,-1,orders.getOrderNo(),accountShop.getFreezeKaiyuan(),"普通用户华宝货款购买库存积分",35, userSarket.getUserId());
								this.insertLogKaiyuanFreeze(0,payKaiYuan,-1,orders.getOrderNo(),accountShop.getFreezeKaiyuan(),"华宝货款购买库存积分的手续费和税率支出",36, userSarket.getUserId());
							//	accountShop.setFreezeKaiyuan(accountShop.getFreezeKaiyuan().add(kaiyuan).subtract(payKaiYuan).subtract(feeKaiYuan));
							}else {
								this.insertLogKaiYuanTurnover(35,0,userSarket.getUserId(),orders.getOrderNo(),accountShop.getKaiyuanTurnover(),-1,payKaiYuan,"非普通用户华宝货款购买库存积分");
								this.insertLogKaiYuanTurnover(35,0,userSarket.getUserId(),orders.getOrderNo(),accountShop.getKaiyuanTurnover(),-1,feeKaiYuan,"华宝货款购买库存积分的手续费和税率支出");
							//	accountShop.setKaiyuanTurnover(accountShop.getKaiyuanTurnover().add(orders.getKaiyuan()));
							}
							insertStockScore(orders.getOrderNo(), userSarket.getUserId(), 6, payKaiYuan.add(feeKaiYuan), BigDecimal.ZERO, BigDecimal.ZERO, payKaiYuan, feeKaiYuan, score, "库存积分不足订单结算系统自动购买");
							this.insertLogStockScore(1,0,userSarket.getUserId(),orders.getOrderNo(),accountShop.getStockScore(),-1,score,"库存积分不足订单结算系统自动购买");

						}
						Map<String, Object> map = this.getAfterSevenWorkDay(7);
						String  endDays=map.get("endDay").toString().substring(0,10);
						SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
						String time = format.format(new Date());
						String  newTime=endDays+" "+time;
						SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
						Date newDate  = sdf.parse(newTime );
						sktOrdersExtension.setSettleTime(newDate);
						sktOrdersExtensionService.updateById(sktOrdersExtension);
					}
					orders.setIsClosed(1);							//订单结束
					orders.setBatFlag(2);                  			//批处理标示符：1未处理 2已处理 9处理中
					orders.setOrderStatus(2);                     // 用户确认收货
					orders.setReceiveTime(new Date());                  // 收货时间
					ordersMapper.updateById(orders);
                    List<Integer> usersIds=new ArrayList<Integer>();
                    usersIds.add(accountShop.getUserId());
                    //发送系统消息
                    messagesService.addMessages(1,1,usersIds,"订单【"+orders.getOrderNo()+"】用户已确认收货",null);
                    //生成订单记录表
                    this.insertLogOrders(orderId,2,"用户已收货",userId,0);
				//	ordersMapper.selectById(orders);
				}

			}
                return true;
             } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
	}

	/**   插入积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	public boolean insertLogScore(int fromId,int type, String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScore logScore=new LogScore();
		logScore.setCreateTime(new Date());
		logScore.setDataFlag(1);
		logScore.setFromId(fromId);
		logScore.setOrderNo(orderNo);
		logScore.setPreScore(preScore);
		logScore.setRemark(remark);
		logScore.setScore(score);
		logScore.setScoreType(scoreType);
        logScore.setType(type);
		logScore.setUserId(userId);
		Integer flag = logScoreMapper.insert(logScore);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

	/** 华宝流水
	 * @param fromId
	 * @param kaiyuan
	 * @param kaiyuanType
	 * @param orderNo
	 * @param preKaiyuan
	 * @param remark
	 * @param type
	 * @param userId
	 * @return
	 */
	public boolean insertLogKaiyuan(Integer fromId,BigDecimal kaiyuan,Integer kaiyuanType,String orderNo,BigDecimal preKaiyuan,String remark,Integer type,Integer userId){
		LogKaiyuan logKaiyuan=new LogKaiyuan();
		logKaiyuan.setCreateTime(new Date());
		logKaiyuan.setFromId(fromId);
		logKaiyuan.setKaiyuan(kaiyuan);
		logKaiyuan.setKaiyuanType(kaiyuanType);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuan.setOrderNo(orderNo);
		logKaiyuan.setPreKaiyuan(preKaiyuan);
		logKaiyuan.setRemark(remark);
		logKaiyuan.setType(type);
		logKaiyuan.setUserId(userId);
		int flag=logKaiyuanMapper.insert(logKaiyuan);//华宝消费记录
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
	/**  现金流水
	 * @param cashType
	 * @param fromId
	 * @param userId
	 * @param firstNum
	 * @param preCash
	 * @param remark
	 * @param type
	 * @param cash
	 * @return
	 */
	public boolean insertLogCash(Integer cashType,Integer fromId,Integer userId ,String orderNo,BigDecimal preCash,String remark,Integer type,BigDecimal cash){
		LogCash logCash=new LogCash();
		logCash.setCashType(cashType);
		logCash.setCreateTime(new Date());
		logCash.setDataFlag(1);
		logCash.setFromId(fromId);
		logCash.setUserId(userId);
		// 创建订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logCash.setOrderNo(orderNo);
		logCash.setPreCash(preCash);
		logCash.setRemark(remark);
		logCash.setType(type);
		logCash.setCash(cash);
		int flag=logCashMapper.insert(logCash);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
	/** 消费奖励
	 * @param inviteId 推荐人id
	 *   @param  score   积分
	 * @return
	 */
	@Override
	public Integer saleAward(int inviteId,BigDecimal score,int usetId ,String orderNo){
		Account account=am.selectAccountByuserId(inviteId);//推荐人账户
		Users user = usersMapper.selectById(inviteId);//推荐人
		int userType =user.getUserType();
		SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("consumeProfit");
		String fieldValue = sysConfig.getFieldValue();
		BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
		BigDecimal getScore=score.multiply(percent);

		if(userType==0){
			//代发积分流水
			this.insertLogScoreFreeze(usetId,4,orderNo,account.getFreezeScore(),"下线消费获得",getScore,1,inviteId);
			account.setFreezeScore(account.getFreezeScore().add(getScore));
		}else{
			//积分流水
			this.insertLogScore(usetId, 4,orderNo, account.getScore(), "下线消费获得", getScore, 1, inviteId);
			account.setScore(account.getScore().add(getScore));
			account.setTotalScore(account.getTotalScore().add(getScore));
		}
		return	am.updateById(account);
	}

	/**
	 * 销售奖励
	 * @param inviteId
	 * @param score
	 * @param userId
	 * @return
	 */
	@Override
	public Integer marketAward(int inviteId,BigDecimal score, int userId,String orderNo){
		Account account=am.selectAccountByuserId(inviteId);//推荐人账户
		Users user = usersMapper.selectById(inviteId);//推荐人
		int userType =user.getUserType();
		SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("turnoverProfit");
		String fieldValue = sysConfig.getFieldValue();
		BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
		BigDecimal getScore=score.multiply(percent);

		if(userType==0){
			//代发积分流水
			this.insertLogScoreFreeze(userId,5,orderNo,account.getFreezeScore(),"线下商家消费获得",getScore,1,inviteId);
			account.setFreezeScore(account.getFreezeScore().add(getScore));
		}else{
			//积分流水
			this.insertLogScore(userId, 5,orderNo, account.getScore(), "下线营业额获得", getScore, 1, inviteId);
			account.setTotalScore(account.getTotalScore().add(getScore));
			account.setScore(account.getScore().add(getScore));
		}
		return	am.updateById(account);


	}

	// 将待发积分转入正式积分
	public Integer FreezeToFormal(Integer userId, BigDecimal score, Boolean isManager) {
		LogScore logScore = new LogScore();

		// 支出人为平台设置为0
		logScore.setFromId(userId);
		// 收入人为此用户
		logScore.setUserId(userId);
		// 积分类型为 待发转入正式12
		logScore.setType(12);
		// 生成订单号
		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String strDate = sfDate.format(new Date());
		String num = GetOrderNum.getRandom620(2);
		logScore.setOrderNo("3" + strDate + num);
		// 操作前金额要到数据库查询account表中的实时金额，将userId传过去
		Account account = am.findScoreById(userId);
		// 用户操作前金额
		logScore.setPreScore(account.getScore());
		// 流水标志：加积分所以类型为 1
		logScore.setScoreType(1);
		// 操作金额
		logScore.setScore(score);
		// 备注
		if (isManager) {
			logScore.setRemark("普通用户升级为经理,划拨特别奖励,积分流水");
		} else {
			logScore.setRemark("普通用户升级为主管,划拨特别奖励,积分流水");
		}
		// 创建时间
		logScore.setCreateTime(new Date());
		// 添加积分记录
		Integer insert = logScoreMapper.insert(logScore);
		// 将待发积分该为零
		account.setFreezeScore(new BigDecimal(0));
		// 将用户账户表中积分添加变化金额
		account.setScore(account.getScore().add(score));
		// 将用户获得的积分添加到用户累计获得中去
		account.setTotalScore(account.getTotalScore().add(score));
		// 修改用户账户
		Integer update = am.updateByUserId2(account);
		return update;
	}

	// 将待发现金转入正式
	public Integer cashFrrezeToFormal(Integer userId, BigDecimal cash, Boolean isManager) {
		// 生成现金流水
		LogCash logCash = new LogCash();
		logCash.setCashType(1);
		logCash.setCreateTime(new Date());
		logCash.setDataFlag(1);
		logCash.setFromId(userId);
		logCash.setUserId(userId);
		// 创建订单号
		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String strDate3 = sfDate.format(new Date());
		String num3 = GetOrderNum.getRandom620(2);
		logCash.setOrderNo("3" + strDate3 + num3);
		// 操作前金额要到数据库查询account表中的实时金额，将userId传过去
		Account account = am.findScoreById(userId);
		logCash.setPreCash(account.getCash());
		if (isManager) {
			logCash.setRemark("普通用户升级为经理，待发现金转为可用现金");
		} else {
			logCash.setRemark("普通用户升级为主管，待发现金转为可用现金");
		}
		logCash.setType(4);
		logCash.setCash(account.getFreezeCash());
		logCashMapper.insert(logCash);
		// 将待发现金该为零
		account.setFreezeCash(new BigDecimal(0));
		// 将用户账户表中积分添加变化金额
		account.setCash(account.getCash().add(cash));
		// 将用户获得的积分添加到用户累计获得中去
		account.setTotalCash(account.getTotalCash().add(cash));
		// 修改用户账户
		Integer update = am.updateByUserId3(account);
		return update;
	}

	// 华宝营业额流水表
	public Integer hbTurnover(Integer type, Integer fromId, Integer userId, String orderNo, Integer kaiyuanType,
			BigDecimal kaiyuan, String remark) {
		LogKaiyuanTurnover logKaiyuanTurnover = new LogKaiyuanTurnover();
		logKaiyuanTurnover.setType(type);
		logKaiyuanTurnover.setFromId(fromId);
		logKaiyuanTurnover.setUserId(userId);
		// 生成订单号
		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String strDate = sfDate.format(new Date());
		String num = GetOrderNum.getRandom620(2);
		logKaiyuanTurnover.setOrderNo(orderNo);
		// 实时查询用户操作前金额
		AccountShop findKaiyuanTurnover = accountShopMapper.findKaiyuanTurnover(userId);
		// 操作前金额
		logKaiyuanTurnover.setPreKaiyuan(findKaiyuanTurnover.getKaiyuanTurnover());
		// k流水标志
		logKaiyuanTurnover.setKaiyuanType(kaiyuanType);
		logKaiyuanTurnover.setKaiyuan(kaiyuan);
		logKaiyuanTurnover.setRemark(remark);
		logKaiyuanTurnover.setCreateTime(new Date());
		// 添加记录
		Integer insert = logKaiyuanTurnoverMapper.insert(logKaiyuanTurnover);
		// 修改商家账户表
		this.updateKaiyuanByuserId(findKaiyuanTurnover, kaiyuan);
		return insert;
	}

	/**
	 * 修改商家账户表
	 */
	public Integer updateKaiyuanByuserId(AccountShop findKaiyuanTurnover, BigDecimal kaiyuan) {
		// 添加华宝货款
		findKaiyuanTurnover.setKaiyuanTurnover(findKaiyuanTurnover.getKaiyuanTurnover().add(kaiyuan));
		// 增加累计获得华宝货款
		findKaiyuanTurnover.setTotalKaiyuanTurnover(findKaiyuanTurnover.getTotalKaiyuanTurnover().add(kaiyuan));
		// 将待发华宝货款清零
		findKaiyuanTurnover.setFreezeKaiyuan(new BigDecimal(0));
		Integer update = accountShopMapper.updateKaiyuanByuserId(findKaiyuanTurnover);
		return update;
	}
	/** 代发华宝流水
	 * @param fromId
	 * @param kaiyuan
	 * @param kaiyuanType
	 * @param orderNo
	 * @param preKaiyuan
	 * @param remark
	 * @param type
	 * @param userId
	 * @return
	 */
	public boolean insertLogKaiyuanFreeze(Integer fromId,BigDecimal kaiyuan,Integer kaiyuanType,String ordeNo,BigDecimal preKaiyuan,String remark,Integer type,Integer userId){
		LogKaiyuanFreeze logKaiyuanFreeze=new LogKaiyuanFreeze();
		logKaiyuanFreeze.setCreateTime(new Date());
		logKaiyuanFreeze.setFromId(fromId);
		logKaiyuanFreeze.setKaiyuan(kaiyuan);
		logKaiyuanFreeze.setKaiyuanType(kaiyuanType);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuanFreeze.setOrderNo(ordeNo);
		logKaiyuanFreeze.setPreKaiyuan(preKaiyuan);
		logKaiyuanFreeze.setRemark(remark);
		logKaiyuanFreeze.setType(type);
		logKaiyuanFreeze.setUserId(userId);
		int flag=logKaiyuanFreezeMapper.insert(logKaiyuanFreeze);//代发华宝消费记录
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
	/**   插入待发积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	public boolean insertLogScoreFreeze(int fromId, int type,String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScoreFreeze logScoreFreeze=new LogScoreFreeze();
		logScoreFreeze.setCreateTime(new Date());
		logScoreFreeze.setDataFlag(1);
		logScoreFreeze.setFromId(fromId);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScoreFreeze.setOrderNo(orderNo);
		logScoreFreeze.setPreScore(preScore);
		logScoreFreeze.setRemark(remark);
		logScoreFreeze.setScore(score);
		logScoreFreeze.setScoreType(scoreType);
		logScoreFreeze.setUserId(userId);
        logScoreFreeze.setType(type);
		Integer flag = logScoreFreezeMapper.insert(logScoreFreeze);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
	/**   特别奖励
	 * @param list  接受奖励的用户id
	 * @param specialPer
	 * @param score
	 * @param specialType

	 * @return
	 */
	@Override
	public void specialAward(List<Integer> list,BigDecimal specialPer,BigDecimal score,Integer specialType,int inviteId,String orderNo){
		BigDecimal score1=score.multiply(specialPer);
		SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("specialProfit");
		BigDecimal specialProfit=new BigDecimal(sysConfig.getFieldValue()).divide(new BigDecimal(100));;
		//特别奖励
		String specialFirstNum="";
        String specialRemark="";
        int specialScoreType=0;
        //待发积分
        String ScoreFreezefirstNum="";
        int  ScoreFreezeType=0;
        String ScoreFreezeRemark="";
        int   ScoreFreezeScoreType=0;
        //积分流水
        String  scoreFirstNum="";
        String   scoreRemark="";
        int  scoreType=0;
        int  scoreScoreType=0;

		if (specialType==1){//1消费获得的待发特别奖励
            specialFirstNum="1";
            specialRemark="消费获得的待发特别奖励";
            specialScoreType=1;
            ScoreFreezefirstNum="1";
            ScoreFreezeType=6;
            ScoreFreezeRemark="特别奖励";
            ScoreFreezeScoreType=1;
            scoreType=6;
            scoreFirstNum="3";
            scoreRemark="特别奖励";
            scoreScoreType=1;
        }
        if (specialType==2){//消售获得的待发特别奖励
            specialFirstNum="1";
            specialRemark="消售获得的待发特别奖励";
            specialScoreType=1;
            ScoreFreezefirstNum="6";
            ScoreFreezeType=6;
            ScoreFreezeRemark="特别奖励";
            ScoreFreezeScoreType=1;
            scoreType=6;
            scoreFirstNum="3";
            scoreRemark="特别奖励";
            scoreScoreType=1;
        }
        if (specialType==31){//31转到正式账号的特别奖励
            specialFirstNum="3";
            specialRemark="转到正式账号的特别奖励";
            specialScoreType=-1;

            ScoreFreezefirstNum="3";
            ScoreFreezeType=31;
            ScoreFreezeRemark="转入到正式积分账户";
            ScoreFreezeScoreType=-1;

            scoreType=15;
            scoreFirstNum="3";
            scoreRemark="待发特别奖励转入";
            scoreScoreType=1;
        }
		if(list.size()>0){
			int i=-1;
			for(Integer id:list){
				if( i!=-1){
					inviteId=list.get(i);
				}
				i++;
				score1=score1.multiply(specialProfit);
				if(score1.compareTo(new BigDecimal("1"))==-1){
					break;
				}
				Users user = usersMapper.selectById(id);//推荐人
				Account account = am.selectAccountByuserId(id);//推荐人账户
                BigDecimal preFreezeScore=new BigDecimal("0.0000");
               if(account.getFreezeScore()!=null){
                    preFreezeScore=account.getFreezeScore();
                }
                BigDecimal preScore=new BigDecimal("0.0000");
                if(account.getScore()!=null){
                    preScore=account.getScore();
                }
                BigDecimal preScoreSpecial=new BigDecimal("0.00");

                if(account.getOne()!=null){
                    preScoreSpecial= preScoreSpecial.add(account.getOne());
                }
                if(account.getTwo()!=null){
                    preScoreSpecial= preScoreSpecial.add(account.getTwo());
                }
                if(account.getThree()!=null){
                    preScoreSpecial=  preScoreSpecial.add(account.getThree());
                }
                if(account.getFour()!=null){
                    preScoreSpecial=preScoreSpecial.add(account.getFour());
                }
                if(account.getFive()!=null){
                    preScoreSpecial= preScoreSpecial.add(account.getFive());
                }
				int inviteNum=account.getInviteNum();

                if (user.getUserType()==0){ //普通用户
					if (inviteNum>=5){ //推荐主管或者经理人数大于等于5
						//待发积分流水------
                        insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score1,1, id);
						account.setFreezeScore(account.getFreezeScore().add(score1));
                        account.setTotalScore(account.getTotalScore().add(score1));
                        am.updateById(account);
					}else {
						BigDecimal score2=score1.divide(new BigDecimal(5));
						if(inviteNum==0){
							account.setOne(account.getOne().add(score2));
							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==1){
                            insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2,1, id);

                            account.setFreezeScore(account.getFreezeScore().add(score2));

							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==2){
                            insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2.multiply(new BigDecimal(2)),1, id);

                            account.setFreezeScore(account.getFreezeScore().add(score2.multiply(new BigDecimal(2))));

                            account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==3){
                            insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2.multiply(new BigDecimal(3)),1, id);
                            account.setFreezeScore(account.getFreezeScore().add(score2.multiply(new BigDecimal(3))));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==4){
                            insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2.multiply(new BigDecimal(4)),1, id);
                            account.setFreezeScore(account.getFreezeScore().add(score2.multiply(new BigDecimal(4))));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}
                        //待发特别奖励积分流水---------------------
                        insertLogScoreSpecial(specialType,inviteId, orderNo,preScoreSpecial,specialRemark,score1, 1,id);
					}
				}else{
					if (inviteNum>=5){ //推荐主管或者经理人数大于等于5
						//积分流水------
                        insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score1,1,id);
						account.setScore(account.getScore().add(score1));
                        account.setTotalScore(account.getTotalScore().add(score1));
                        am.updateById(account);
					}else {
						BigDecimal score2=score1.divide(new BigDecimal(5));
						if(inviteNum==0){
							account.setOne(account.getOne().add(score2));
							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==1){
                            insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2,1,id);
							account.setScore(account.getScore().add(score2));
                            account.setTotalScore(account.getTotalScore().add(score2));
							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==2){
                            insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2.multiply(new BigDecimal(2)),1,id);
							account.setScore(account.getScore().add(score2.multiply(new BigDecimal(2))));
                            account.setTotalScore(account.getTotalScore().add(score2.multiply(new BigDecimal(2))));
                            account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==3){
                            insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2.multiply(new BigDecimal(3)),1,id);
							account.setScore(account.getScore().add(score2.multiply(new BigDecimal(3))));
                            account.setTotalScore(account.getTotalScore().add(score2.multiply(new BigDecimal(3))));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}else if(inviteNum==4){
                            insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2.multiply(new BigDecimal(4)),1,id);
							account.setScore(account.getScore().add(score2.multiply(new BigDecimal(4))));
                            account.setTotalScore(account.getTotalScore().add(score2.multiply(new BigDecimal(4))));
							account.setFive(account.getFive().add(score2));
                            am.updateById(account);
						}
                        //待发特别奖励积分流水---------------------
                        insertLogScoreSpecial(specialType,inviteId, orderNo,preScoreSpecial,specialRemark,score1, 1,id);
					}
				}
               //
			}
		}

	}

    @Override
    public boolean uptateKaiyuanByUserId(Map<String, Object> map) {
		int i=am.uptateKaiyuanByUserId(map);
		if (i!=1){
			return false;
		}
		return true;
    }

	@Override
	public boolean uptateCashByUserId(Map<String, Object> cashMap) {
		int i=am.uptateCashByUserId(cashMap);
		if (i!=1){
			return false;
		}
		return true;
	}

	/**   插入特别奖励积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	public boolean insertLogScoreSpecial( int type,int fromId, String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScoreSpecial logScoreSpecial=new LogScoreSpecial();
		logScoreSpecial.setType(type);
		logScoreSpecial.setCreateTime(new Date());
		logScoreSpecial.setDataFlag(1);
		logScoreSpecial.setFromId(fromId);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScoreSpecial.setOrderNo(orderNo);
		logScoreSpecial.setPreScore(preScore);
		logScoreSpecial.setRemark(remark);
		logScoreSpecial.setScore(score);
		logScoreSpecial.setScoreType(scoreType);
		logScoreSpecial.setUserId(userId);
		Integer flag = logScoreSpecialMapper.insert(logScoreSpecial);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
    // 代发现金记录
    public Integer freezeCashToFormal(Integer type,Integer fromId,Integer
            userId,String orderNo, BigDecimal preCash,
                                      Integer cashType, BigDecimal cash, String remark) {
        LogCashFreeze logCashFreeze = new LogCashFreeze();
        logCashFreeze.setType(type);
        logCashFreeze.setFromId(fromId);
        logCashFreeze.setUserId(userId);
        // 生成订单号
//        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//        String strDate = sfDate.format(new Date());
//        String num = GetOrderNum.getRandom620(2);
        logCashFreeze.setOrderNo(orderNo);
        // 操作前金额
        logCashFreeze.setPreCash(preCash);
        logCashFreeze.setCashType(cashType);
        logCashFreeze.setCash(cash);
        logCashFreeze.setRemark(remark);
        logCashFreeze.setCreateTime(new Date());
        // 添加待发现金记录
        Integer insert = logCashFreezeMapper.insert(logCashFreeze);
        return insert;
    }

    // 修改用户待发现金
    public Integer updateFreezeCash(Account account, BigDecimal freezeCash) {
        account.setFreezeCash(account.getFreezeCash().add(freezeCash));
        account.setInviteNum(account.getInviteNum() + 1);
        // 修改
        Integer update = am.updateFreezeCash(account);
        return update;
    }


//    // 修改用户现金
//    public Integer updateCash(Account account, BigDecimal cash){
//        account.setCash(account.getCash().add(cash));
//        account.setTotalCash(account.getTotalCash().add(cash));
//        account.setInviteNum(account.getInviteNum() + 1);
//        // 修改
//        Integer update = am.updateCash(account);
//        this.selectSpecial2(account.getUserId());
//        return update;
//    }

    //用户账户添加待发积分
    public Integer addFreezeScore(Account account){
        Integer add = am.addFreezeScore(account);
        return add;
    }

    //用户账户添加积分
    public Integer addScore(Account account){
        Integer add = am.updateScore(account);
        return add;
    }

    /**
     * 数据报表
     * @param userId
     * @return
     */
    @Override
    public  BaseTable  getDataTable(Integer userId){
        BaseTable baseTable=new BaseTable();

		BigDecimal todayDraws = am.getTodayDraws(userId);
		BigDecimal todayHuabao = am.getTodayHuabao(userId);
		BigDecimal todayOrders = am.getTodayOrders(userId);
		BigDecimal todayOrdersStores = am.getTodayOrdersStores(userId);
		BigDecimal todayScore = am.getTodayScore(userId);
		BigDecimal todayRecharge = am.getTodayRecharge(userId);

		BigDecimal mouthDraws = am.getMouthDraws(userId);
		BigDecimal mouthHuabao = am.getMouthHuabao(userId);
		BigDecimal mouthOrders = am.getMouthOrders(userId);
		BigDecimal mouthOrdersStores = am.getMouthOrdersStores(userId);
		BigDecimal mouthRecharge = am.getMouthRecharge(userId);
		BigDecimal mouthScore = am.getMouthScore(userId);


		BigDecimal totalScore = am.getTotalScore(userId);
		BigDecimal totalDraws = am.getTotalDraws(userId);
		BigDecimal totalHuabao = am.getTotalHuabao(userId);
		BigDecimal totalOrders = am.getTotalOrders(userId);
		BigDecimal totalOrdersStores = am.getTotalOrdersStores(userId);
		BigDecimal totalRecharge = am.getTotalRecharge(userId);
		if(todayDraws==null){
			todayDraws=BigDecimal.ZERO;
		}
		if(mouthDraws==null){
			mouthDraws=BigDecimal.ZERO;
		}
		if(totalDraws==null){
			totalDraws=BigDecimal.ZERO;
		}
        baseTable.setTodayDraws(todayDraws);
        baseTable.setMouthDraws(mouthDraws);
        baseTable.setTotalDraws(totalDraws);
		if(todayHuabao==null){
			todayHuabao=BigDecimal.ZERO;
		}
		if(mouthHuabao==null){
			mouthHuabao=BigDecimal.ZERO;
		}
		if(totalHuabao==null){
			totalHuabao=BigDecimal.ZERO;
		}

        baseTable.setTodayHuabao(todayHuabao);
        baseTable.setMouthHuabao(mouthHuabao);
        baseTable.setTotalHuabao(totalHuabao);
		if(todayRecharge==null){
			todayRecharge=BigDecimal.ZERO;
		}
		if(mouthRecharge==null){
			mouthRecharge=BigDecimal.ZERO;
		}
		if(totalRecharge==null){
			totalRecharge=BigDecimal.ZERO;
		}
        baseTable.setTodayRecharge(todayRecharge);
        baseTable.setMouthRecharge(mouthRecharge);
        baseTable.setTotalRecharge(totalRecharge);
		if(todayScore==null){
			todayScore=BigDecimal.ZERO;
		}
		if(mouthScore==null){
			mouthScore=BigDecimal.ZERO;
		}
		if(totalScore==null){
			totalScore=BigDecimal.ZERO;
		}
        baseTable.setTodayScore(todayScore);
        baseTable.setMouthScore(mouthScore);
        baseTable.setTotalScore(totalScore);
		if(todayOrders==null){
			todayOrders=BigDecimal.ZERO;
		}
		if(todayOrdersStores==null){
			todayOrdersStores=BigDecimal.ZERO;
		}
		if(mouthOrders==null){
			mouthOrders=BigDecimal.ZERO;
		}
		if(mouthOrdersStores==null){
			mouthOrdersStores=BigDecimal.ZERO;
		}
		if(totalOrders==null){
			totalOrders=BigDecimal.ZERO;
		}
		if(totalOrdersStores==null){
			totalOrdersStores=BigDecimal.ZERO;
		}

        BigDecimal todaySale=todayOrders.add(todayOrdersStores);
        BigDecimal mouthSale=mouthOrders.add(mouthOrdersStores);
        BigDecimal totalSale=totalOrders.add(totalOrdersStores);
        baseTable.setTodaySale(todaySale);
        baseTable.setMouthSale(mouthSale);
        baseTable.setTotalSale(totalSale);
        return baseTable;
    }

	/**
	 * 确认代理申请
	 * @param shaId 股东申请表id
	 * @param staffId  操作员id
	 * @return
	 */
	public String doUpAgent(Integer shaId,Integer staffId) {
		try{
			AgentsApplys agentsApplys = agentsApplysMapper.selectById(shaId);
			int userId = agentsApplys.getUserId();
			SktAgentsStockholder sktAgentsStockholder = agentsStockholderMapper.selectByUserId(userId);
			if(sktAgentsStockholder!=null){
				return "该用户已经是股东";
			}

			int agentId = agentsApplys.getAgentId();
			int type = agentsApplys.getType();
			SktAgentsAccount agentsAccount =
					agentsAccountMapper.findAgentAccountById(agentId);
			Account account = am.selectAccountByuserId(userId);
			BigDecimal money = agentsApplys.getMoney();
			if (type != 6 && type != 7) {
				SktAgentsStockholder agentsStockholder = new
						SktAgentsStockholder();
				agentsStockholder.setAgentId(agentId);
				agentsStockholder.setType(type);
				Integer countStcokManger =
						agentsStockholderMapper.selectCountStcokManger(agentsStockholder);
				if (type == 1 && countStcokManger == 1) {
					return "董事长职位已满";
				} else if (type == 2 && countStcokManger == 1) {
					return "总裁职位已满";
				} else if (type == 3 && countStcokManger == 1) {
					return "行政职位已满";
				} else if (type == 4 && countStcokManger == 1) {
					return "财务职位已满";
				} else if (type == 5 && countStcokManger == 3) {
					return "部门经理职位已满";
				}
				agentsApplys.setBatFlag(1);
				Date batTime = agentsApplys.getBatTime();
				Calendar c = Calendar.getInstance();
				c.setTime(batTime);//设置日历时间
				c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
				agentsApplys.setTestTime(c.getTime());
			//	agentsApplys.setBatTime(c.getTime());
				agentsApplysMapper.updateById(agentsApplys);
				insertLogScoreFreeze(0, 2, agentsApplys.getOrderNo(), account.getFreezeScore(), "升级代理", money.multiply(new BigDecimal("100")), 1, userId);
				account.setFreezeScore(money.multiply(new BigDecimal("100")));
				am.updateById(account);
			} else {
				SktAgents agents = agentsMapper.selectById(agentId);
				SktAgentsStockholder agentsStockholder = new
						SktAgentsStockholder();
				agentsStockholder.setAgentId(agentId);
				agentsStockholder.setType(type);
				  if (type == 7 && agents.getLPsurplusStockNum() ==0) {
					return "普通股东已满";
				}
				//修改申请表
				agentsApplys.setTwoCheckTime(new Date());
				agentsApplys.setStatus(3);
				agentsApplys.setTwoCheckStaffId(staffId);
				agentsApplysMapper.updateById(agentsApplys);

				Users users = usersMapper.selectById(userId);
				users.setIsAgent(type);
				usersMapper.updateById(users);//修改用户代理状态
				Integer countIsStore = usersMapper.selectCountIsStore
						(userId);
				//生成代理公司股东表
				agentsStockholder.setCreateTime(new Date());
				agentsStockholder.setStockNum(agentsApplys.getStockNum());
				agentsStockholder.setStoreNum(countIsStore);
				agentsStockholder.setUserId(userId);
				agentsStockholderMapper.insert(agentsStockholder);
				//修改代理公司表
				agents.setStockNum(agents.getStockNum() + 1);
				agents.setStoreNum(agents.getStoreNum() + countIsStore);
				if(type==7){
					agents.setLPsurplusStockNum(agents.getLPsurplusStockNum() -
							agentsApplys.getStockNum());
				}else if(type==5){
					agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-2);
				}else if(type==4){
					agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-3);
				}else if(type==3){
					agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-3);
				}else if(type==2){
					agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-4);
				}else if(type==1){
					agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-5);
				}

				agentsMapper.updateById(agents);
				//修改代理公司账户表


				if (agentsAccount.getRunFlag() == 1) {//代理公司账号是否开启
					//代理公司积分流水表
					insertScoreAgent(1, agentId, "2",
                    agentsAccount.getScore(), 1, money.multiply(new BigDecimal("100")), "股东申请通过，代理公司获得");
                    agentsAccount.setScore(agentsAccount.getScore
									().add(money.multiply(new BigDecimal("100"))));
					agentsAccount.setTotalScore
							(agentsAccount.getTotalScore().add(money.multiply(new BigDecimal("100"))));
				} else {
					//代理公司待发流水表
					insertLogScoreFreeze(0, 2, agentsApplys.getOrderNo(),
							agentsAccount.getFreezeScore(), "升级代理", money.multiply(new BigDecimal("100")), 1,
							agentId);
					agentsAccount.setFreezeScore
							(agentsAccount.getFreezeScore().add(money.multiply(new BigDecimal("100"))));
				}
				agentsAccountMapper.updateById(agentsAccount);
				//给自己发积分
				BigDecimal score = BigDecimal.ZERO;
				score = money.multiply(new BigDecimal("100"));
//				int countNotHolder =
//						agentsStockholderMapper.selectCountNotHolder(agentId);
//				if (countNotHolder <= 3) {
//					score = money.multiply(new BigDecimal("200"));
//				} else {
//					score = money.multiply(new BigDecimal("100"));
//				}

				//给自己添加   的积分流水
				this.insertLogScore(0, 9, agentsApplys.getOrderNo(), account.getScore(), "升级代理公司股东，赠送积分到积分账户", score, 1, userId);
				account.setScore(account.getScore().add(score));
				account.setTotalScore(account.getTotalScore().add(score));
				am.updateById(account);

				//给上线发积分（经理或者代理）
				int inviteId = users.getInviteId();
				if (inviteId != 0) {
					Users inviteUsers = usersMapper.selectById
							(inviteId);
					if (inviteUsers.getUserType() == 2 &&
							inviteUsers.getIsAgent() != 0) {
						Account accountInvite =
								am.selectAccountByuserId(inviteId);
						BigDecimal doubelScore = money.multiply(new
								BigDecimal("200"));
						this.insertLogScore(userId, 10, agentsApplys.getOrderNo(),
								accountInvite.getScore(), "下线升级代理奖励", doubelScore, 1, inviteId);
						accountInvite.setScore
								(accountInvite.getScore().add(doubelScore));
						accountInvite.setTotalScore
								(accountInvite.getTotalScore().add(doubelScore));
						am.updateById(accountInvite);
					}
				}
				//如果是主管申请代理判断下线7个工作日内是否有代理申请通过
				if (users.getUserType() == 1) {
					List<AgentsApplys> list = getAgentsApplysSevenAgo
							(userId);
					if (list != null && list.size() > 0) {
						BigDecimal sumScore = BigDecimal.ZERO;
						BigDecimal sumScoreFreeze =
								BigDecimal.ZERO;
						for (AgentsApplys AgentsApply : list) {
							if (AgentsApply.getType() == 7) {
								sumScore = sumScore.add
										(AgentsApply.getMoney().multiply(new BigDecimal("200")));
							} else if (AgentsApply.getType() !=
									7 && AgentsApply.getType() != 6) {
								sumScoreFreeze =
										sumScoreFreeze.add(AgentsApply.getMoney().multiply(new BigDecimal("200")));
							}
						}
						if(sumScoreFreeze.compareTo(BigDecimal.ZERO)==1){
							this.insertLogScoreFreeze(userId, 10, agentsApplys.getOrderNo(),
									account.getFreezeScore(), "下线升级代理奖励", sumScoreFreeze, 1, userId);
							account.setFreezeScore
									(account.getFreezeScore().add(sumScoreFreeze));
						}
						if(sumScore.compareTo(BigDecimal.ZERO)==1){
							this.insertLogScore(userId, 10, agentsApplys.getOrderNo(),
									account.getScore(), "下线升级代理奖励", sumScore, 1, userId);
							account.setScore(account.getScore().add
									(sumScore));
							account.setTotalScore
									(account.getTotalScore().add(sumScore));
						}
						am.updateById(account);
					}
				}
				this.fenRun(agentId,shaId);
			}
			return "操作成功";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "操作失败";
		}

	}

	//线下支付
	@Override
	public Integer underLinePay(UsersRecharge recharge) {
		//如果备注为空默认填写
		if(recharge.getRemark() == "" || recharge.getRemark() == null){
			recharge.setRemark("线下充值");
		}
		//将订单状态改为已上传图片
		recharge.setStatus(2);
		//将支付方式改为线下现金支付
		recharge.setPayType(1);
		Integer update = usersRechargeMapper.updateById(recharge);
		return update;
	}

	//积分转换华宝
//	@Transactional
//	@Override
//	public SktDateTransform scoreTransform(Integer agentId,BigDecimal ratio,Integer userId,Integer type) {
//		//转换积分
//		BigDecimal transformNum = new BigDecimal(0);
//		//转换成华宝
//		BigDecimal kaiyuan = new BigDecimal(0);
//		//判断是用户转换还是代理公司	1是消费者 2是代理公司
//		if(type == 1){
//			//查询用户积分判断是否是否大于一万
//			Account account = am.findScoreById(userId);
//			if(account.getScore().compareTo(new BigDecimal(10000))==1 || account.getScore().compareTo(new BigDecimal(10000))==0){
//				//转换积分数
//				transformNum = account.getScore().setScale(0, BigDecimal.ROUND_DOWN);
//				//转换成华宝的数量
//				kaiyuan = transformNum.divide(new BigDecimal(10000)).setScale(0, BigDecimal.ROUND_DOWN).multiply(ratio).setScale(3, BigDecimal.ROUND_DOWN);
//				//生成积分记录
//				this.insertLogScore(0,31,"2",account.getScore(),"转化华宝减少",kaiyuan,-1,userId);
//				//生成华宝记录
//				this.insertLogKaiyuan(0,kaiyuan,1,"2",account.getKaiyuan(),"转换获得",1,userId);
//				//修改用户账户表
//				account.setUserId(userId);
//				account.setKaiyuan(account.getKaiyuan().add(kaiyuan));
//				account.setTotalKaiyuan(account.getTotalKaiyuan().add(kaiyuan));
//				account.setScore(account.getScore().subtract(kaiyuan));
//				am.updateScoreToKaiyuan(account);
//			}else{
//				return null;
//			}
//		}else{
//			//查询代理公司积分判断是否大于一万
//			SktAgentsAccount sktAgentsAccount = sktAgentsAccountMapper.findAgentAccountById(agentId);
//			if(sktAgentsAccount.getScore().compareTo(new BigDecimal(10000))==1 || sktAgentsAccount.getScore().compareTo(new BigDecimal(10000))==0){
//				//转换积分数
//				transformNum = sktAgentsAccount.getScore().setScale(0, BigDecimal.ROUND_DOWN);
//				//转换成华宝的数量
//				kaiyuan = transformNum.divide(new BigDecimal(10000)).setScale(0, BigDecimal.ROUND_DOWN).multiply(ratio).setScale(3, BigDecimal.ROUND_DOWN);
//				//生成代理公司积分记录
//				this.insertScoreAgent(31,agentId,"2",sktAgentsAccount.getScore(),-1,kaiyuan,"转换华宝减少");
//				//生成代理公司华宝记录
//				this.insertKaiyuanAgent(1,agentId,"2",sktAgentsAccount.getKaiyuan(),1,kaiyuan,"转换获得");
//				//修改代理公司账户表
//				sktAgentsAccount.setAgentId(agentId);
//				sktAgentsAccount.setKaiyuan(sktAgentsAccount.getKaiyuan().add(kaiyuan));
//				sktAgentsAccount.setTotalKaiyuan(sktAgentsAccount.getTotalKaiyuan().add(kaiyuan));
//				sktAgentsAccount.setScore(sktAgentsAccount.getScore().subtract(kaiyuan));
//				sktAgentsAccountMapper.updateScoreToKaiyuan(sktAgentsAccount);
//			}else{
//				return null;
//			}
//		}
//		SktDateTransform sktDateTransform = new SktDateTransform();
//		sktDateTransform.setTransformNum(transformNum);
//		sktDateTransform.setKaiyuan(kaiyuan);
//		return sktDateTransform;
//	}

	//股东分红
//	@Override
//	@Transactional
//	public void shareBonus(Integer agentId) {
//		//查询上次分红月份
//		SktSysConfigs lastDividendMonth = sktSysConfigsMapper.selectSysConfigsByFieldCode("lastDividendMonth");
//		//分红周期
//		SktSysConfigs dividendPeriod = sktSysConfigsMapper.selectSysConfigsByFieldCode("dividendPeriod");
//		//下个分红月份
//		int nextShareBonus = Integer.parseInt(lastDividendMonth.getFieldValue())+Integer.parseInt(dividendPeriod.getFieldValue());
//		//解决跨年问题
//		if(nextShareBonus > 12){
//			nextShareBonus = nextShareBonus - 12;
//		}
//		//当前月份
//		int nowMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
//		//判断当前月份是不是分红月份
//		if(nowMonth == nextShareBonus){
//			//查询代理公司信息
//			SktAgents sktAgents = agentsMapper.findAgent(agentId);
//			//股东总数
//			Integer totalNum = sktAgents.getTotalNum();
//			//当前股东
//			Integer stockNum = sktAgents.getStockNum();
//			//商家总数
//			Integer totalStoreNum = sktAgents.getTotalStoreNum();
//			//当前商家
//			Integer storeNum = sktAgents.getStoreNum();
//			//计算商家完成度
//			int finishSeller = storeNum * 100 / totalStoreNum;
//			//计算股东完成度
//			int finishShareholder = stockNum * 100 / totalNum;
//			//完成度都是100
//			if(finishSeller  >= 100 && finishShareholder == 100){
//				//处理
//				this.finishHundred(sktAgents, lastDividendMonth.getFieldValue(), dividendPeriod.getFieldValue());
//			}
//			//完成度是70-100之间
//			if(((finishSeller >= 70 && finishSeller <= 100) && (finishShareholder >= 70 && finishShareholder < 100)) ||
//					((finishSeller >= 70 && finishSeller < 100) && (finishShareholder >= 70 && finishShareholder <= 100))){
//				dealMore(sktAgents, lastDividendMonth.getFieldValue(), dividendPeriod.getFieldValue());
//			}
//			//完成度小于70
//			if(finishSeller < 70 || finishShareholder < 70){
//				dealLess(sktAgents, lastDividendMonth.getFieldValue(), dividendPeriod.getFieldValue());
//			}
//		}
//	}

//	@Transactional
//	private void finishHundred(SktAgents sktAgents, String lastDividendMonth, String dividendPeriod) {
//		Integer agentId = sktAgents.getAgentId();
//		List<SktAgentsStockholder> sktAgentsStockholderList = sktAgentsStockholderMapper.getByAgentId(agentId);
//		for (SktAgentsStockholder sktAgentsStockholder1:
//			 sktAgentsStockholderList) {
//			//全部完成的分红系数
//			BigDecimal threeRatio = sktAgents.getThreeRatio();
//
//			//level为代理级别，10省，11市，12区县
//			Integer level = sktAgents.getAlevel();
//			//创建map准备存储省市县id
//			Map<String, Object> map = new HashMap<String, Object>();
//			//省
//			if(level == 10){
//				//省id
//				Integer provinceId = sktAgents.getProvinceId();
//				map.put("provinceId", provinceId);
//				this.finishHundredMain(threeRatio, map, sktAgents, sktAgentsStockholder1, lastDividendMonth, dividendPeriod);
//			}
//			//市
//			if(level == 11){
//				int cityId = sktAgents.getCityId();
//				map.put("cityId", cityId);
//				this.finishHundredMain(threeRatio, map, sktAgents, sktAgentsStockholder1, lastDividendMonth, dividendPeriod);
//			}//区县
//			if(level == 12){
//				int areaId = sktAgents.getAreaId();
//				map.put("areaId", areaId);
//				this.finishHundredMain(threeRatio, map, sktAgents, sktAgentsStockholder1, lastDividendMonth, dividendPeriod);
//			}
//		}
//	}

//	@Transactional
//	private void finishHundredMain(BigDecimal threeRatio, Map<String, Object> map, SktAgents sktAgents,
//								   SktAgentsStockholder stockHolder, String lastDividendMonth, String dividendPeriod) {
//
//		List<SktShops> shopList = sktShopsMapper.getShopByLevelId(map);
//		String dividendRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("DividendRatio").getFieldValue();
//
//		for (SktShops shop : shopList) {
//			if (shop == null) {
//				return;
//			}
//
//			// 需要查询当月总销售额，根据分红周期计算==========================================================================
//			// 查询月销售额
//			Map<String, Object> sMap = new HashMap();
//			// 算出上次分红的时间
//			SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
//			Calendar cale = Calendar.getInstance();
//			cale.setTime(new Date());
//			Date c = cale.getTime();
//			String nowTime = format.format(c);
//			cale.add(Calendar.MONTH, -Integer.valueOf(dividendPeriod));
//			Date m = cale.getTime();
//			String LastDividentTime = format.format(m);
//
//			sMap.put("nowTime", nowTime);
//			sMap.put("LastDividentTime", LastDividentTime);
//			sMap.put("shopId", shop.getShopId());
//
//			BigDecimal totalTurnover = sktSalesMonthMapper.getSalesMonth(sMap);
//			if (totalTurnover == null) {
//				return;
//			}
//
//			// 分红百分比
//
//			BigDecimal rate = new BigDecimal(Integer.valueOf(dividendRatio) / 100);
//
//			// 最终金额
//			totalTurnover = totalTurnover.multiply(rate);
//			// 总股份数
//			int totalStock = sktAgents.getTotalStockNum();
//			// 股东持有份数
//			int stock = stockHolder.getStockNum();
//
//			// 完成100%总积分
//			BigDecimal totalScoreThree = threeRatio.multiply(totalTurnover)
//					.divide(new BigDecimal(totalStock), 10, ROUND_HALF_DOWN).multiply(new BigDecimal(stock));
//
//			Account account = am.getByUserId(stockHolder.getUserId());
//			BigDecimal preScore = account.getTotalScore();
//			BigDecimal freezeScore = account.getFreezeScore();
//
//			// 获取股东分红人数
//			SktSysConfigs config = sktSysConfigsMapper.selectSysConfigsByFieldCode("holderDividendNum");
//			int holderDividendNum = Integer.valueOf(config.getFieldValue());
//			int storeNum = stockHolder.getStoreNum();
//
//			// 完成直推商家任务
//			if (storeNum >= holderDividendNum) {
//				account.setScore(totalScoreThree);
//				account.setTotalScore(totalScoreThree);
//				// 股东日志
//				LogScore logScore = new LogScore();
//				logScore.setType(11);
//				logScore.setScore(totalScoreThree);
//				logScore.setRemark("股东分红积分增加");
//				this.addScoreLog(logScore,account,preScore);
//			}
//
//			// 未完成直推商家任务
//			if (storeNum < holderDividendNum) {
//				account.setFreezeScore(totalScoreThree);
//				// 记日志
//				LogScoreFreeze logScoreFreezeLess = new LogScoreFreeze();
//				logScoreFreezeLess.setType(15);
//				logScoreFreezeLess.setScore(totalScoreThree);
//				logScoreFreezeLess.setRemark("股东分红冻结积分增加");
//				addLogScoreFreeze(logScoreFreezeLess, account, freezeScore);
//			}
//
//			// 取都是score，更新正式更新totalscore和score，冻结更新freezeScore
//			am.updateBonusScore(account);
//
//			// 更新股东分红表
//			stockHolder.setLastDividend(totalScoreThree);
//			stockHolder.setDividendTime(new Date());
//			stockHolder.setTotalDividend(totalScoreThree.add(stockHolder.getTotalDividend()));
//
//			sktAgentsStockholderMapper.update2(stockHolder);
//		}
//	}

    //购买库存积分记录
    @Transactional
    public Integer buyStockScore(String firstNum, Integer userId, Integer payType, BigDecimal totalMoney, BigDecimal realMoney,
                                 BigDecimal cash, BigDecimal kaiyuan, BigDecimal kaiyuanFee, BigDecimal score, String orderRemarks, JSONObject json) {
        SktOrdersStockscore sktOrdersStockscore = new SktOrdersStockscore();
        // 生成订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        sktOrdersStockscore.setOrderNo(firstNum + strDate + num);
        sktOrdersStockscore.setUserId(userId);
        sktOrdersStockscore.setPayType(payType);
        sktOrdersStockscore.setTotalMoney(totalMoney);
        sktOrdersStockscore.setRealMoney(realMoney);
        sktOrdersStockscore.setCash(cash);
        sktOrdersStockscore.setKaiyuan(kaiyuan);
        sktOrdersStockscore.setKaiyuanFee(kaiyuanFee);
        sktOrdersStockscore.setScore(score);
        sktOrdersStockscore.setOrderRemarks(orderRemarks);
        sktOrdersStockscore.setCreateTime(new Date());
        Integer insert = sktOrdersStockscoreMapper.insert(sktOrdersStockscore);
        json.put("orderId", sktOrdersStockscore.getOrderId());
        json.put("orderNo",sktOrdersStockscore.getOrderNo());
        return insert;
    }

    //修改购买库存积分状态
    @Transactional
    public Integer updateOrderStockScore(Integer userId, Integer orderStatus, Integer payType, BigDecimal cash, BigDecimal kaiyuan, BigDecimal realMoney, BigDecimal kaiyuanFree) {
        try{
			AccountShopDTO accountShopDTO = accountShopMapper.findAccountByUserId(userId);
			SktOrdersStockscore sktOrdersStockscore = new SktOrdersStockscore();
			sktOrdersStockscore.setUserId(accountShopDTO.getUserId());
			sktOrdersStockscore.setOrderStatus(orderStatus);
			sktOrdersStockscore.setPayType(payType);
			if (cash != null) {
				sktOrdersStockscore.setCash(cash);
			}
			if (kaiyuan != null) {
				sktOrdersStockscore.setKaiyuan(kaiyuan);
			}
			if (kaiyuanFree != null) {
				sktOrdersStockscore.setKaiyuanFee(kaiyuanFree);
			}
			Integer update = sktOrdersStockscoreMapper.updateStockScoreById(sktOrdersStockscore);
			return update;
		}catch (Exception e){
			e.printStackTrace();
			return 0;
		}
    }

    //添加库存记录
	@Transactional
    public Integer insertLogStockScore(Integer type,Integer fromId,Integer userId,String orderNo,BigDecimal preScore,Integer scoreType,BigDecimal score,String remark){
        LogStockscore logStockscore = new LogStockscore();
        logStockscore.setType(type);
        logStockscore.setFromId(fromId);
        logStockscore.setUserId(userId);
        // 生成订单号
//        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//        String strDate = sfDate.format(new Date());
//        String num = GetOrderNum.getRandom620(2);
        logStockscore.setOrderNo(orderNo);
        logStockscore.setPreScore(preScore);
        logStockscore.setScoreType(scoreType);
        logStockscore.setScore(score);
        logStockscore.setRemark(remark);
        logStockscore.setCreateTime(new Date());
        Integer insert = logStockscoreMapper.insert(logStockscore);
        return insert;
    }

    //待发现金记录
//	public Integer insertLogCashFreeze(Integer type,Integer fromId,Integer userId,String firstNum,BigDecimal preCash,Integer cashType,BigDecimal cash,String remark){
//		LogCashFreeze logCashFreeze = new LogCashFreeze();
//		logCashFreeze.setType(type);
//		logCashFreeze.setFromId(fromId);
//		logCashFreeze.setUserId(userId);
//		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
//		logCashFreeze.setOrderNo(firstNum + strDate + num);
//		logCashFreeze.setPreCash(preCash);
//		logCashFreeze.setCashType(cashType);
//		logCashFreeze.setCash(cash);
//		logCashFreeze.setRemark(remark);
//		logCashFreeze.setCreateTime(new Date());
//		Integer insert = logCashFreezeMapper.insert(logCashFreeze);
//		return insert;
// 		}

	//代理公司积分记录
	@Transactional
	public Integer insertScoreAgent(Integer type,Integer agentId,String orderNo,BigDecimal preScore,Integer scoreType,BigDecimal score,String remark){
		LogScoreAgent logScoreAgent = new LogScoreAgent();
		logScoreAgent.setType(type);
		logScoreAgent.setAgentId(agentId);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScoreAgent.setOrderNo(orderNo);
		logScoreAgent.setPreScore(preScore);
		logScoreAgent.setScoreType(scoreType);
		logScoreAgent.setScore(score);
		logScoreAgent.setRemark(remark);
		logScoreAgent.setCreateTime(new Date());
		Integer insert = logScoreAgentMapper.insert(logScoreAgent);
		return insert;
	}

	//代理公司开元宝记录
	@Transactional
	public Integer insertKaiyuanAgent(Integer type,Integer agentId,String orderNo,BigDecimal preKaiyuan,Integer kaiyuanType,BigDecimal kaiyuan,String remark){
		LogKaiyuanAgent logKaiyuanAgent = new LogKaiyuanAgent();
		logKaiyuanAgent.setType(type);
		logKaiyuanAgent.setAgentId(agentId);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuanAgent.setOrderNo(orderNo);
		logKaiyuanAgent.setPreKaiyuan(preKaiyuan);
		logKaiyuanAgent.setKaiyuanType(kaiyuanType);
		logKaiyuanAgent.setKaiyuan(kaiyuan);
		logKaiyuanAgent.setRemark(remark);
		logKaiyuanAgent.setCreateTime(new Date());
		Integer insert = logKaiyuanAgentMapper.insert(logKaiyuanAgent);
		return insert;
	}

//	@Transactional
//	public Integer selectSpecial(Integer userId,Boolean isManager){
//        //需要取出来的代发积分总金额
//        BigDecimal score = new BigDecimal(0);
//        //实时查询用户账户
//        Account account = am.findScoreById(userId);
//		//待发特别奖励操作前金额
//		BigDecimal preScore = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
//        if(account.getInviteNum() > 0 && account.getInviteNum() < 6){
//            if(account.getInviteNum() == 1){
//                score = account.getOne();
//                account.setOne(new BigDecimal(0));
//            }else if(account.getInviteNum() == 2){
//                score = account.getOne().add(account.getTwo());
//                account.setOne(new BigDecimal(0));
//                account.setTwo(new BigDecimal(0));
//            }else if(account.getInviteNum() == 3){
//                score = account.getOne().add(account.getTwo()).add(account.getThree());
//                account.setOne(new BigDecimal(0));
//                account.setTwo(new BigDecimal(0));
//                account.setThree(new BigDecimal(0));
//            }else if(account.getInviteNum() == 4){
//                score = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour());
//                account.setOne(new BigDecimal(0));
//                account.setTwo(new BigDecimal(0));
//                account.setThree(new BigDecimal(0));
//                account.setFour(new BigDecimal(0));
//            }else if(account.getInviteNum() == 5){
//                score = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
//                account.setOne(new BigDecimal(0));
//                account.setTwo(new BigDecimal(0));
//                account.setThree(new BigDecimal(0));
//                account.setFour(new BigDecimal(0));
//                account.setFive(new BigDecimal(0));
//            }
//            if(isManager){
//                //生成代发转出记录
//                this.insertLogScoreSpecial(31,userId,"3",preScore,"普通用户升级为经理，划拨特别奖励,转到待发账号的特别奖励",score,-1,userId);
//                //生成积分流水
//                this.insertLogScore(userId,15,"3",account.getScore(),"普通用户升级为经理,划拨特别奖励,积分流水",score,1,userId);
//            }else{
//                //生成代发转出记录
//                this.insertLogScoreSpecial(31,userId,"3",preScore,"普通用户升级为主管，划拨特别奖励,转到待发账号的特别奖励",score,-1,userId);
//                //生成积分流水
//                this.insertLogScore(userId,15,"3",account.getScore(),"普通用户升级为主管,划拨特别奖励,积分流水",score,1,userId);
//            }
//            //修改用户账户
//            account.setScore(account.getScore().add(score));
//            account.setTotalScore(account.getTotalScore().add(score));
//            Integer update = am.updateScore(account);
//            return update;
//        }
//        return 0;
//    }

    //下线升级，发放待发特别奖励
//	@Transactional
//	public Integer selectSpecial2(Integer userId){
//		//需要取出来的代发积分总金额
//		BigDecimal score = new BigDecimal(0);
//		//实时查询用户账户
//		Account account = am.findScoreById(userId);
//		//待发特别奖励操作前金额
//		BigDecimal preScore = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
//		if(account.getInviteNum() > 0 && account.getInviteNum() < 6){
//			if(account.getInviteNum() == 1){
//				score = account.getOne();
//				account.setOne(new BigDecimal(0));
//			}else if(account.getInviteNum() == 2){
//				score = account.getOne().add(account.getTwo());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//			}else if(account.getInviteNum() == 3){
//				score = account.getOne().add(account.getTwo()).add(account.getThree());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//				account.setThree(new BigDecimal(0));
//			}else if(account.getInviteNum() == 4){
//				score = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//				account.setThree(new BigDecimal(0));
//				account.setFour(new BigDecimal(0));
//			}else if(account.getInviteNum() == 5){
//				score = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//				account.setThree(new BigDecimal(0));
//				account.setFour(new BigDecimal(0));
//				account.setFive(new BigDecimal(0));
//			}
//				//生成代发转出记录
//				this.insertLogScoreSpecial(31,0,"3",preScore,"特别奖励，划拨到正式",score,-1,userId);
//				//生成积分流水
//				this.insertLogScore(0,15,"3",account.getScore(),"特别奖励，划拨到正式",score,1,userId);
//				//修改用户账户
//				account.setScore(account.getScore().add(score));
//				account.setTotalScore(account.getTotalScore().add(score));
//				Integer update = am.updateScore(account);
//				return update;
//		}
//		return 0;
//	}


	//查询前7个工作日
	public  Map<String,Object> getSevenWorkDay(){
		Map<String,Object> map=new HashMap<>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		String format = sdf.format(new Date());
		Integer date=Integer.parseInt(format);
		List<SktDate> days = am.getSevenWorkDay(date);
		int endDay=0;
		int startDay=0;
		if(days!=null && days.size()>0){
			endDay=days.get(0).getDate();
			startDay=days.get(days.size()-1).getDate();
		}
		String startDay1=startDay+"";
		String startYaer=startDay1.substring(0,4);
		String startMouth=startDay1.substring(4,6);
		String startDate=startDay1.substring(6,8);
		String newStart=startYaer+"-"+startMouth+"-"+startDate+" "+"00:00:00";
		String endDay1=endDay+"";
		String endYaer=endDay1.substring(0,4);
		String endMouth=endDay1.substring(4,6);
		String endDate=endDay1.substring(6,8);
		String newEnd=endYaer+"-"+endMouth+"-"+endDate+" "+"23:59:59";
		map.put("startDay",newStart);
		map.put("endDay",newEnd);
		return  map;
	}

	/**
	 * 查询前7个工作日申请代理通过
	 * @return
	 */
	public List<AgentsApplys> getAgentsApplysSevenAgo(Integer userId){
		Map<String,Object> map=getSevenWorkDay();
		map.put("userId",userId);
		List<AgentsApplys> list = agentsApplysMapper.getAgentsApplysSevenAgo(map);
		return  list;

	}

	/**
	 * 代理申请成功分润
	 * @param agentId 代理id
	 * @param shaId  股东申请id
	 */
	public void fenRun(Integer agentId,Integer shaId){

		SktAgentsAccount agentsAccount=agentsAccountMapper.findAgentAccountById(agentId);
		AgentsApplys agentsApplys = agentsApplysMapper.selectById(shaId);
		BigDecimal money=agentsApplys.getMoney();
		SktAgents agents = agentsMapper.selectById(agentId);
		BigDecimal a=new BigDecimal(agents.getStockNum());
		BigDecimal b=new BigDecimal(agents.getTotalStockNum());
		Double f=a.divide(b, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
		SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("holderDividendNum");
		String fieldValue = sysConfig.getFieldValue();
		Integer holderDividendNum=Integer.parseInt(fieldValue);
		if(agentsAccount.getRunFlag()==0){
			if(f>=0.5){
				this.insertScoreAgent(32,agentId,agentsApplys.getOrderNo(),agentsAccount.getScore(),1,agentsAccount.getFreezeScore(),"待发积分转正式积分");
				insertLogScoreFreeze(0,2,agentsApplys.getOrderNo(),agentsAccount.getFreezeScore(),"待发积分转正式积分",money.multiply(new BigDecimal("100")),-1,agentId);
				agentsAccount.setRunFlag(1);
				agentsAccount.setScore(agentsAccount.getScore().add(agentsAccount.getFreezeScore()));
				agentsAccount.setTotalScore(agentsAccount.getTotalScore().add(agentsAccount.getFreezeScore()));
				agentsAccount.setFreezeScore(BigDecimal.ZERO);
				agentsAccountMapper.updateById(agentsAccount);

			}
		}
		BigDecimal c=new BigDecimal(agents.getStoreNum());
		BigDecimal d=new BigDecimal(agents.getTotalStoreNum());
		double perStore= c.divide(d,2, BigDecimal.ROUND_HALF_UP).doubleValue();
		if(f>=0.7 && perStore>=0.7){
			List<SktAgentsStockholder> list = agentsStockholderMapper.selectByAgentId(agentId);
			if(list!=null && list.size()>0){
				BigDecimal twoFreezeDividend=list.get(0).getTwoFreezeDividend();
				if(twoFreezeDividend.compareTo(BigDecimal.ZERO)==1){
					for (SktAgentsStockholder agentsStockholder:list){
						Integer userId=agentsStockholder.getUserId();
						int totalStockNum=agents.getTotalStockNum();
						BigDecimal twoRatio=agents.getTwoRatio();
						int stockNum=agentsStockholder.getStockNum();
						Account account = am.selectAccountByuserId(userId);
						Integer countIsStore = usersMapper.selectCountIsStore(userId);
						if(countIsStore>=holderDividendNum){
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTwoFreezeDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getTwoFreezeDividend(),-1,userId);
							this.insertLogScore(userId,11,agentsApplys.getOrderNo(),agentsStockholder.getTwoFreezeDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getTwoFreezeDividend(),1,userId);

							account.setScore(account.getScore().add(agentsStockholder.getTwoFreezeDividend()));
							account.setTotalScore(account.getTotalScore().add(agentsStockholder.getTwoFreezeDividend()));
							agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
							am.updateById(account);
							agentsStockholderMapper.updateById(agentsStockholder);
						}else{
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getTotalDividend(),1,userId);
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getTotalDividend(),-1,userId);
							agentsStockholder.setStoreFreezeDividend(agentsStockholder.getStoreFreezeDividend().add(agentsStockholder.getTwoFreezeDividend()));
							agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
							agentsStockholderMapper.updateById(agentsStockholder);
						}


					}

				}
			}
		}
		if(f>=1.0 && perStore>=1.0){
			List<SktAgentsStockholder> list = agentsStockholderMapper.selectByAgentId(agentId);
			if(list!=null && list.size()>0){
				BigDecimal threeFreezeDividend=list.get(0).getThreeFreezeDividend();
				if(threeFreezeDividend.compareTo(BigDecimal.ZERO)>=0){
					for (SktAgentsStockholder agentsStockholder:list){
						Integer userId=agentsStockholder.getUserId();
						int totalStockNum=agents.getTotalStockNum();
						BigDecimal twoRatio=agents.getTwoRatio();
						int stockNum=agentsStockholder.getStockNum();
						Account account = am.selectAccountByuserId(userId);
						Integer countIsStore = usersMapper.selectCountIsStore(userId);
						if(countIsStore>=holderDividendNum){
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getThreeFreezeDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getThreeFreezeDividend(),-1,userId);
							this.insertLogScore(userId,11,agentsApplys.getOrderNo(),agentsStockholder.getThreeFreezeDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getThreeFreezeDividend(),1,userId);

							account.setScore(account.getScore().add(agentsStockholder.getThreeFreezeDividend()));
							account.setTotalScore(account.getTotalScore().add(agentsStockholder.getThreeFreezeDividend()));
							agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
							am.updateById(account);
							agentsStockholderMapper.updateById(agentsStockholder);
						}else{
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getTotalDividend(),1,userId);
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getTotalDividend(),-1,userId);
							agentsStockholder.setStoreFreezeDividend(agentsStockholder.getStoreFreezeDividend().add(agentsStockholder.getThreeFreezeDividend()));
							agentsStockholder.setThreeFreezeDividend(BigDecimal.ZERO);
							agentsStockholderMapper.updateById(agentsStockholder);
						}

					}
				}
			}
		}
	}
	/**  用户升级点击确认支付
	 * * @param userId   用户id
	 * @param userUpType 用户升级后角色
	 * @return
	 */
	public JSONObject getCashToUp(Integer userId, Integer userUpType){
		JSONObject json = new JSONObject();
		Account account = am.selectAccountByuserId(userId);
		BigDecimal cash = account.getCash();
		UsersUpgrade usersUpgrade=new UsersUpgrade();
//		UsersDTO usersDTO = new UsersDTO();
//		usersDTO.setUserId(userId);
//		UsersDTO usersDT = usersService.selectOneUsersInfo(usersDTO);
        Users user = usersMapper.selectById(userId);
		BigDecimal upAccount=BigDecimal.ZERO;
		if (user != null) {
			int userType = user.getUserType();
			json.put("cash", cash);
			if (userType == 0 && userUpType == 1) {
				upAccount=new BigDecimal("997.00");
				json.put("upAccount", "997.00");
				usersUpgrade.setRealMoney(new BigDecimal(997));
				//	json.put("upAgentScore", "99700.00");
			} else if (userType == 0 && userUpType == 2) {
				upAccount=new BigDecimal("9997.00");
				json.put("upAccount", "9997.00");
				usersUpgrade.setRealMoney(new BigDecimal(9997));
				//json.put("upManagerScore", "999700.00");

			} else if (userType == 1 && userUpType == 2) {
				upAccount=new BigDecimal("9000.00");
				json.put("upAccount", "9000.00");
				//json.put("upManagerScore", "900000.00");
				usersUpgrade.setRealMoney(new BigDecimal(9000));
			}

			usersUpgrade.setOrderNo(StringUtils.getOrderIdByTime("3"));
			usersUpgrade.setUserId(userId);
			usersUpgrade.setPreRole(userType);
			usersUpgrade.setAfterRole(userUpType);
			usersUpgrade.setPayType(2);
			usersUpgrade.setTotalMoney(upAccount);
		//	usersUpgrade.setRealMoney(BigDecimal.ZERO);
			usersUpgrade.setCash(BigDecimal.ZERO);
			usersUpgrade.setKaiyuan(BigDecimal.ZERO);
			usersUpgrade.setKaiyuanFee(BigDecimal.ZERO);
			usersUpgrade.setOrderRemarks("用户升级");
			usersUpgrade.setCreateTime(new Date());
			usersUpgrade.setDataFlag(1);
			usersUpgrade.setStatus(0);
			usersUpgradeService.insert(usersUpgrade);
//			usersUpgradeService.addUserUpgradeInfo(usersUpgrade);
//            Integer userUpOrderId = usersUpgradeService.selectMaxOrderIdByUserId(userId);
            json.put("code", "01");
			json.put("msg", "成功");
            json.put("orderId", usersUpgrade.getOrderId());
			json.put("allowPayType","2,4");
		}
		return  json;
	}
	private void addScoreLog(LogScore logScore, Account account, BigDecimal preScore) {

		logScore.setFromId(0);
		logScore.setUserId(account.getUserId());
		logScore.setOrderNo("");// 订单号为空
		logScore.setPreScore(preScore);
		logScore.setScoreType(1);
		logScore.setDataFlag(1);
		logScore.setCreateTime(new Date());
		logScoreMapper.insert(logScore);

	}

	@Transactional
	private void addLogScoreFreeze(LogScoreFreeze logScoreFreeze, Account account, BigDecimal preScore){

		logScoreFreeze.setFromId(0);
		logScoreFreeze.setUserId(account.getUserId());
		logScoreFreeze.setOrderNo("");// 订单号为空
		logScoreFreeze.setPreScore(preScore);
		logScoreFreeze.setScoreType(1);
		logScoreFreeze.setDataFlag(1);
		logScoreFreeze.setCreateTime(new Date());
		logScoreFreezeMapper.insert(logScoreFreeze);
	}

    /**
     * 回显用户数据
     * @param userId
     * @return
     */
		@Override
		public AccountList  getAccountByUserId(Integer userId){
			Users users = usersMapper.selectById(userId);
			Map<String, Object> map = usersRealnameMapper.selectUserCardId(userId);
			Account account =am.selectAccountByuserId(userId);
            BigDecimal sumScoreSpecial=BigDecimal.ZERO;
            AccountList accountList=new AccountList();
			if(account!=null){
                sumScoreSpecial =account.getOne().add(account.getTwo().add(account.getThree().add(account.getFour().add(account.getFive()))));
                BeanUtils.copyProperties(account,accountList);
                accountList.setSumScoreSpecial(sumScoreSpecial);

            }
            accountList.setUserType(users.getUserType());
            accountList.setIsAgent(users.getIsAgent());
            accountList.setIsShop(users.getIsShop());
            accountList.setIsStore(users.getIsStore());



			if(map!=null && map.size()>0){
                accountList.setAuditStatus(Integer.parseInt(map.get("auditStatus").toString()));
            }

			return accountList;
		}

	/**
	 * 两个完成度都在百分之七十到百分之一百之间
	 *
	 * @param agent
	 * @param lastDividendMonth
	 * @param dividendPeriod
	 * @throws Exception
	 */

//	@Transactional
//	private void dealMore(SktAgents agent, String lastDividendMonth, String dividendPeriod){
//
//		int agentId = agent.getAgentId();
//
//		List<SktAgentsStockholder> stockHolderList = agentsStockholderMapper.getByAgentId(agentId);
//
//		for (SktAgentsStockholder stockHolder : stockHolderList) {
//			// 完成70%(落地)的分红系数
//			BigDecimal twoRatio = agent.getTwoRatio();
//			// 全部完成的分红系数
//			BigDecimal threeRatio = agent.getThreeRatio();
//
//			Map<String, Object> map = new HashMap<String, Object>();
//
//			int level = agent.getAlevel();
//			// level为代理级别，10省，11市，12区县
//			// 省
//			if (level == 10) {
//
//				int provinceId = agent.getProvinceId();
//				map.put("provinceId", provinceId);
//				dealMoreMain(twoRatio, threeRatio, map, agent, stockHolder, lastDividendMonth, dividendPeriod);
//			}
//
//			// 市
//			if (level == 11) {
//
//				int cityId = agent.getCityId();
//				map.put("cityId", cityId);
//				dealMoreMain(twoRatio, threeRatio, map, agent, stockHolder, lastDividendMonth, dividendPeriod);
//			}
//
//			// 区县
//			if (level == 12) {
//
//				int areaId = agent.getAreaId();
//				map.put("areaId", areaId);
//				dealMoreMain(twoRatio, threeRatio, map, agent, stockHolder, lastDividendMonth, dividendPeriod);
//			}
//		}
//	}

//	@Transactional
//	private void dealMoreMain(BigDecimal twoRatio, BigDecimal threeRatio, Map<String, Object> map, SktAgents agent,
//							  SktAgentsStockholder stockHolder, String lastDividendMonth, String dividendPeriod){
//
//
//		List<SktShops> shopList = sktShopsMapper.getShopByLevelId(map);
//		for (SktShops shop : shopList) {
//			if (shop == null) {
//				return;
//			}
//
//			// 查询月销售额
//			Map<String, Object> sMap = new HashMap();
//			// 算出上次分红的时间
//			SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
//			Calendar cale = Calendar.getInstance();
//			cale.setTime(new Date());
//			Date c = cale.getTime();
//			String nowTime = format.format(c);
//			cale.add(Calendar.MONTH, -Integer.valueOf(dividendPeriod));
//			Date m = cale.getTime();
//			String LastDividentTime = format.format(m);
//
//			sMap.put("nowTime", nowTime);
//			sMap.put("LastDividentTime", LastDividentTime);
//			sMap.put("shopId", shop.getShopId());
//
//			BigDecimal totalTurnover = sktsalesMonthService.getSalesMonth(sMap);
//			if (totalTurnover == null) {
//				return;
//			}
//
//			// 分红百分比
//			String dividendRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("DividendRatio").getFieldValue();
//			BigDecimal rate = new BigDecimal(Integer.valueOf(dividendRatio) / 100);
//
//			// 最终金额
//			totalTurnover = totalTurnover.multiply(rate);
//			// 总股份数
//			int totalStock = agent.getTotalStockNum();
//			// 股东持有份数
//			int stock = stockHolder.getStockNum();
//
//			// 完成70%总积分
//			BigDecimal totalScoreTwo = twoRatio.multiply(totalTurnover)
//					.divide(new BigDecimal(totalStock), 10, ROUND_HALF_DOWN).multiply(new BigDecimal(stock));
//			// 完成100%总积分
//			BigDecimal totalScoreThree = threeRatio.subtract(twoRatio).multiply(totalTurnover)
//					.divide(new BigDecimal(totalStock), 10, ROUND_HALF_DOWN).multiply(new BigDecimal(stock));
//
//			Account account = am.getByUserId(stockHolder.getUserId());
//			BigDecimal preScore = account.getTotalScore();
//			BigDecimal freezeScore = account.getFreezeScore();
//
//			// 获取股东分红人数
//			SktSysConfigs config = sktSysConfigsMapper.selectSysConfigsByFieldCode("holderDividendNum");
//			int holderDividendNum = Integer.valueOf(config.getFieldValue());
//			int storeNum = stockHolder.getStoreNum();
//
//			// 完成100%的日志
//			LogScoreFreeze logScoreFreezeAll = new LogScoreFreeze();
//			account.setFreezeScore(totalScoreThree);
//			logScoreFreezeAll.setType(16);
//			logScoreFreezeAll.setScore(totalScoreThree);
//			logScoreFreezeAll.setRemark("股东分红冻结积分增加");
//			addLogScoreFreeze(logScoreFreezeAll, account, freezeScore);
//
//			// 完成直推商家任务
//			if (storeNum >= holderDividendNum) {
//				account.setScore(totalScoreTwo);
//				account.setTotalScore(totalScoreTwo);
//				// 股东日志
//				LogScore logScore = new LogScore();
//				logScore.setType(11);
//				logScore.setScore(totalScoreTwo);
//				logScore.setRemark("股东分红积分增加");
//				addScoreLog(logScore, account, preScore);
//
//			}
//
//			// 完成70%，未完成直推商家任务
//			if (storeNum < holderDividendNum) {
//				account.setFreezeScore(totalScoreThree.add(totalScoreTwo));
//				// 记日志
//				LogScoreFreeze logScoreFreezeLess = new LogScoreFreeze();
//				logScoreFreezeLess.setType(15);
//				logScoreFreezeLess.setScore(totalScoreTwo);
//				logScoreFreezeLess.setRemark("股东分红冻结积分增加");
//				addLogScoreFreeze(logScoreFreezeLess, account, freezeScore.add(totalScoreTwo));
//			}
//
//			// 取都是score，更新正式更新totalscore和score，冻结更新freezeScore
//			am.updateBonusScore(account);
//
//			// 更新股东分红表
//			stockHolder.setLastDividend(totalScoreThree.add(totalScoreTwo));
//			stockHolder.setDividendTime(new Date());
//			stockHolder.setTotalDividend(totalScoreThree.add(totalScoreTwo).add(stockHolder.getTotalDividend()));
//
//			agentsStockholderMapper.update2(stockHolder);
//		}
//	}

	/**
	 * 两个完成度都小于百分之七十
	 *
	 * @param agent
	 * @param lastDividendMonth
	 * @param dividendPeriod
	 * @throws Exception
	 */
//	@Transactional
//	private void dealLess(SktAgents agent, String lastDividendMonth, String dividendPeriod){
//
//		int agentId = agent.getAgentId();
//
//		// 查找股东集合
//		List<SktAgentsStockholder> stockHolderList = agentsStockholderMapper.getByAgentId(agentId);
//
//		// 遍历股东集合
//		for (SktAgentsStockholder stockHolder : stockHolderList) {
//			// 成为股东的分红系数
//			BigDecimal oneRatio = agent.getOneRatio();
//			// 完成70%(落地)的分红系数
//			BigDecimal twoRatio = agent.getTwoRatio();
//			// 全部完成的分红系数
//			BigDecimal threeRatio = agent.getThreeRatio();
//
//			Map<String, Object> map = new HashMap<String, Object>();
//
//			int level = agent.getAlevel();
//			// level为代理级别，10省，11市，12区县
//			// 省
//			if (level == 10) {
//				int provinceId = agent.getProvinceId();
//				map.put("provinceId", provinceId);
//				dealLessMain(oneRatio, twoRatio, threeRatio, map, agent, stockHolder, lastDividendMonth,
//						dividendPeriod);
//			}
//
//			// 市
//			if (level == 11) {
//				int cityId = agent.getCityId();
//				map.put("cityId", cityId);
//				dealLessMain(oneRatio, twoRatio, threeRatio, map, agent, stockHolder, lastDividendMonth,
//						dividendPeriod);
//			}
//
//			// 区县
//			if (level == 12) {
//				int areaId = agent.getAreaId();
//				map.put("areaId", areaId);
//				dealLessMain(oneRatio, twoRatio, threeRatio, map, agent, stockHolder, lastDividendMonth,
//						dividendPeriod);
//			}
//		}
//	}

//	@Transactional
//	private void dealLessMain(BigDecimal oneRatio, BigDecimal twoRatio, BigDecimal threeRatio, Map<String, Object> map,
//							  SktAgents agent, SktAgentsStockholder stockHolder, String lastDividendMonth, String dividendPeriod){
//
//
//		List<SktShops> shopList = sktShopsMapper.getShopByLevelId(map);
//		if (shopList.size() == 0) {
//			return;
//		}
//
//		for (SktShops shop : shopList) {
//
//			// 查询月销售额
//			Map<String, Object> sMap = new HashMap();
//			// 算出上次分红的时间
//			SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
//			Calendar cale = Calendar.getInstance();
//			cale.setTime(new Date());
//			Date c = cale.getTime();
//			String nowTime = format.format(c);
//			cale.add(Calendar.MONTH, -Integer.valueOf(dividendPeriod));
//			Date m = cale.getTime();
//			String LastDividentTime = format.format(m);
//
//			sMap.put("nowTime", nowTime);
//			sMap.put("LastDividentTime", LastDividentTime);
//			sMap.put("shopId", shop.getShopId());
//
//			BigDecimal totalTurnover = sktSalesMonthMapper.getSalesMonth(sMap);
//			if (totalTurnover == null) {
//				return;
//			}
//
//			// 分红百分比
//			String dividendRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("DividendRatio").getFieldValue();
//			BigDecimal rate = new BigDecimal(Integer.valueOf(dividendRatio) / 100);
//			// 最终金额
//			totalTurnover = totalTurnover.multiply(rate);
//			// 总股份数
//			int totalStock = agent.getTotalStockNum();
//			// 股东持有份数
//			int stock = stockHolder.getStockNum();
//
//			// 股东总积分
//			BigDecimal totalScoreOne = oneRatio.multiply(totalTurnover)
//					.divide(new BigDecimal(totalStock), 10, ROUND_HALF_DOWN).multiply(new BigDecimal(stock));
//			// 完成70%总积分
//			BigDecimal totalScoreTwo = twoRatio.subtract(oneRatio).multiply(totalTurnover)
//					.divide(new BigDecimal(totalStock), 10, ROUND_HALF_DOWN).multiply(new BigDecimal(stock));
//			// 完成100%总积分
//			BigDecimal totalScoreThree = threeRatio.subtract(oneRatio).multiply(totalTurnover)
//					.divide(new BigDecimal(totalStock), 10, ROUND_HALF_DOWN).multiply(new BigDecimal(stock));
//
//			Account account = am.getByUserId(stockHolder.getUserId());
//			BigDecimal freezeScore = account.getFreezeScore();
//
//			// 取都是score，更新正式更新totalscore和score，冻结更新freezeScore
//			BigDecimal totalScore = account.getTotalScore();
//			account.setScore(totalScoreOne);
//			account.setTotalScore(totalScoreOne);
//			account.setFreezeScore(totalScoreTwo.add(totalScoreThree));
//			am.updateBonusScore(account);
//
//			// 股东日志
//			LogScore logScore = new LogScore();
//			logScore.setType(11);
//			logScore.setScore(totalScoreOne);
//			logScore.setRemark("股东分红积分增加");
//			addScoreLog(logScore, account, totalScore);
//
//			// 完成70%的日志
//			LogScoreFreeze logScoreFreezeLess = new LogScoreFreeze();
//			logScoreFreezeLess.setType(15);
//			logScoreFreezeLess.setScore(totalScoreTwo);
//			logScoreFreezeLess.setRemark("股东分红冻结积分增加");
//			addLogScoreFreeze(logScoreFreezeLess, account, freezeScore);
//
//			// 完成100%的日志
//			LogScoreFreeze logScoreFreezeAll = new LogScoreFreeze();
//			logScoreFreezeAll.setType(16);
//			logScoreFreezeAll.setScore(totalScoreThree);
//			logScoreFreezeAll.setRemark("股东分红冻结积分增加");
//			BigDecimal preScore = freezeScore.add(totalScoreTwo);
//			addLogScoreFreeze(logScoreFreezeAll, account, freezeScore.add(totalScoreTwo));
//
//			// 更新股东分红表
//			stockHolder.setLastDividend(totalScoreThree.add(totalScoreTwo).add(totalScoreOne));
//			stockHolder.setDividendTime(new Date());
//			stockHolder.setTotalDividend(
//					totalScoreThree.add(totalScoreTwo).add(totalScoreOne).add(stockHolder.getTotalDividend()));
//
//			sktAgentsStockholderMapper.update2(stockHolder);
//		}
//	}

    @Override
	//查询后几个工作日
	public  Map<String,Object> getAfterSevenWorkDay(Integer dates){
		Map<String,Object> map=new HashMap<>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		String format = sdf.format(new Date());
		Integer date=Integer.parseInt(format);
		Map<String,Object> map1=new HashMap<>();
		map1.put("date",date);
		map1.put("dates", dates);
		List<SktDate> days = am.getAfterSevenWorkDay(map1);
		int endDay=0;
		int startDay=0;
		if(days!=null && days.size()>0){
            startDay=days.get(0).getDate();
            endDay=days.get(days.size()-1).getDate();
		}
		String startDay1=startDay+"";
		String startYaer=startDay1.substring(0,4);
		String startMouth=startDay1.substring(4,6);
		String startDate=startDay1.substring(6,8);
		String newStart=startYaer+"-"+startMouth+"-"+startDate+" "+"00:00:00";
		String endDay1=endDay+"";
		String endYaer=endDay1.substring(0,4);
		String endMouth=endDay1.substring(4,6);
		String endDate=endDay1.substring(6,8);
		String newEnd=endYaer+"-"+endMouth+"-"+endDate+" "+"23:59:59";
		map.put("startDay",newStart);
		map.put("endDay",newEnd);
		return  map;
	}

	/**
	 *赠送积分
	 * @param userId
	 * @param shopId
	 * @param score
	 * @param payPwd
	 * @param totalMoney
	 * @param scoreRatio
	 * @return
	 */

	@Transactional
	@Override
	public JSONObject sendScore(Integer userId,Integer shopId,BigDecimal score,String payPwd,BigDecimal totalMoney,Integer scoreRatio,String orderRemarks){
		JSONObject json = new JSONObject();
		//判断用户是否允许购买库存积分
		SktShops sktShops1 = sktShopsService.selectById(shopId);
		Integer usersId=sktShops1.getUserId();
		Users users=usersService.selectById(usersId);
		int isOperation=users.getIsOperation();
		if (isOperation==0){
			json.put("code", "00");
			json.put("msg", "该功能已关闭！");
		}
		Users userSale = usersMapper.selectById(userId);//获得买家对应的user
		if(userSale==null){
			json.put("code","00");
			json.put("msg","无此账户，请重新确认");
			return json;
		}
		AccountShop accountShop =new AccountShop();
		accountShop.setShopId(shopId);
		EntityWrapper<AccountShop> entityWrapper =new EntityWrapper<AccountShop>(accountShop);
		AccountShop accountShop1 = accountShopService.selectOne(entityWrapper);
		if(accountShop1.getUserId()==userId){
			json.put("code","00");
			json.put("msg","对不起，您不能给自己赠送积分");
			return json;
		}
		BigDecimal stockScore=accountShop1.getStockScore();
		if(score.compareTo(stockScore)==1){
			json.put("code","00");
			json.put("msg","赠送积分多余商家库存积分，无法赠送");
			return json;
		}
		Integer shopUserId=accountShop1.getUserId();

		JSONObject jsonObject = usersService.checkPayPassWorld(shopUserId, payPwd);
		if ("00".equals(jsonObject)){
			return jsonObject;
		}else {
			try {
				SktShops sktShops = sktShopsMapper.selectById(shopId);
				Account account =new Account();
				account.setUserId(userId);
				EntityWrapper<Account> ew =new EntityWrapper<Account>(account);
				Account account1 = this.selectOne(ew);
				//生成线下订单
				SktOrdersStores sktOrdersStores = this.insertOrdersStores("1", shopId, userId, 3, 1, 1, totalMoney, totalMoney, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, scoreRatio, score, "商家赠送积分");
				sktOrdersStoresService.insert(sktOrdersStores);
				//买家积分流水，
				this.insertLogScore(shopUserId,1,sktOrdersStores.getOrderNo(), account1.getScore(), "线下商家增送", score, 1, userId);
				account1.setScore(account1.getScore().add(score));//会员积分增加
				account1.setTotalScore(account1.getTotalScore().add(score));
				am.updateById(account1);

				this.insertLogStockScore(4,shopUserId,shopUserId,sktOrdersStores.getOrderNo(),accountShop1.getStockScore(),-1,score,"线下订单发放库存积分");
				accountShop1.setStockScore(accountShop1.getStockScore().subtract(score));//商家积分减少
				accountShop1.setTotalGiveStockScore(accountShop1.getTotalGiveStockScore().add(score));//累计分发库存积分
				accountShopMapper.updateById(accountShop1);


				//是否开启销售奖
				SktSysConfigs sysConfigsisXiaoshou = sysConfigsMapper.selectSysConfigsByFieldCode("isXiaoshou");
				String isXiaoshouValue = sysConfigsisXiaoshou.getFieldValue();
				if("1".equals(isXiaoshouValue)){
					//会员上线消费奖励
					if(userSale.getInviteId()!=0){
						this.saleAward(userSale.getInviteId(), score,userId,sktOrdersStores.getOrderNo());
					}
				}


				//商家上线销售奖
				Users userSarket = usersMapper.selectById(shopUserId);//获得商家对应的user
				//	int userType=userSarket.getUserType();//得判断商家对应用户类型
				//是否开启销费奖
				SktSysConfigs sysConfigsisXiaofei = sysConfigsMapper.selectSysConfigsByFieldCode("isXiaofei");
				String isXiaofeiValue = sysConfigsisXiaofei.getFieldValue();
				if("1".equals(isXiaofeiValue)){
					//8卖家推荐人销售奖
					if(userSarket.getInviteId()!=0){
						this.marketAward(userSarket.getInviteId(),score, userId,sktOrdersStores.getOrderNo());
					}
				}
				SktSysConfigs sysConfigsisOrNoFenrun = sysConfigsMapper.selectSysConfigsByFieldCode("isOrNoFenrun");
				String isOrNoFenrun = sysConfigsisOrNoFenrun.getFieldValue();
				if ("1".equals(isOrNoFenrun)){
					//9.特别奖励
					//9.1 消费特别奖
					List<Integer> ids = usersService.getIds(userId);
					if(ids!=null && ids.size()>0){
						SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("consumeProfit");
						String fieldValue = sysConfig.getFieldValue();
						BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
						specialAward(ids,percent, score,1,userSale.getInviteId(),sktOrdersStores.getOrderNo());
					}
					//9.2销售特别奖
					Integer inviteId = userSarket.getInviteId();
					List<Integer> idss = usersService.getIds(userSarket.getUserId());
					if(idss!=null && idss.size()>0){
						SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("turnoverProfit");
						String fieldValue = sysConfig.getFieldValue();
						BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
						specialAward(idss,percent, score,2,inviteId,sktOrdersStores.getOrderNo());
					}
				}

				List<Integer> usersIds=new ArrayList<Integer>();
				usersIds.add(userId);
				messagesService.addMessages(1,1,usersIds,"商家"+sktShops.getShopName()+"向您赠送了"+score+"积分",null);
				json.put("code","01");
				json.put("msg","下单成功");
			}catch (Exception e){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				json.put("code","00");
				json.put("msg","下单失败");
			}
			return  json;
		}
	}
	//商家华宝货款记录
	public Integer insertLogKaiYuanTurnover(Integer type,Integer fromId,Integer userId,String orderNo,BigDecimal preKaiyuan,Integer kaiyuanType,BigDecimal kaiyuan,String remark){
		LogKaiyuanTurnover logKaiyuanTurnover = new LogKaiyuanTurnover();
		logKaiyuanTurnover.setType(type);
		logKaiyuanTurnover.setFromId(fromId);
		logKaiyuanTurnover.setUserId(userId);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuanTurnover.setOrderNo(orderNo);
		logKaiyuanTurnover.setPreKaiyuan(preKaiyuan);
		logKaiyuanTurnover.setKaiyuanType(kaiyuanType);
		logKaiyuanTurnover.setKaiyuan(kaiyuan);
		logKaiyuanTurnover.setRemark(remark);
		logKaiyuanTurnover.setCreateTime(new Date());
		Integer insert = logKaiyuanTurnoverMapper.insert(logKaiyuanTurnover);
		return insert;
	}

	//点击线下支付
	@Transactional
	@Override
	public UnderLinePay clickUnderLinePay() {
		UnderLinePay underLinePay = new UnderLinePay();
		underLinePay.setRechargeBankName(sysConfigsMapper.selectSysConfigsByFieldCode("rechargeBankName").getFieldValue());
		underLinePay.setRechargeBranchBank(sysConfigsMapper.selectSysConfigsByFieldCode("rechargeBranchBank").getFieldValue());
		underLinePay.setRechargeNo(sysConfigsMapper.selectSysConfigsByFieldCode("rechargeNo").getFieldValue());
		underLinePay.setRechargeReceiver(sysConfigsMapper.selectSysConfigsByFieldCode("rechargeReceiver").getFieldValue());
		underLinePay.setRechargeRemark(sysConfigsMapper.selectSysConfigsByFieldCode("rechargeRemark").getFieldValue());
		return underLinePay;
	}

	/**
	 * 前台购买牌匾
	 * @param sktBuyplaque
	 * @return
	 */
	@Override
	@Transactional
	public JSONObject buyplaque(SktBuyplaque sktBuyplaque){
		JSONObject json = new JSONObject();
		try{
			Integer orderId = sktBuyplaque.getOrderId();
			Integer userId = sktBuyplaque.getUserId();
			Integer payType = sktBuyplaque.getPayType();
			BigDecimal buyplaqueCash=	sktBuyplaque.getCash();
			Account account = am.selectAccountByuserId(userId);
			SktBuyplaque sktBuyplaque1 = sktBuyplaqueMapper.selectById(sktBuyplaque);
			if (payType==2){ //现金账户
				if (sktBuyplaque1.getCash().compareTo(account.getCash())==1){
					json.put("code","00");
					json.put("msg","您的账户现金余额不足，无法购买");
					return json;
				}
				this.insertLogCash(-1,0,userId,sktBuyplaque1.getOrderNo(),account.getCash(),"购买牌匾",38,sktBuyplaque.getCash());
				account.setCash(account.getCash().subtract(sktBuyplaque.getCash()));
				am.updateById(account);
			}else if (payType==3){ //华宝支付
				BigDecimal totalKaiyuan=sktBuyplaque1.getKaiyuan().add(sktBuyplaque1.getKaiyuanFee());
				if (totalKaiyuan.compareTo(account.getKaiyuan())==1){
					json.put("code","00");
					json.put("msg","您的账户华宝余额不足，无法购买");
					return json;
				}
				this.insertLogKaiyuan(0,sktBuyplaque.getKaiyuan(),38,sktBuyplaque1.getOrderNo(),account.getKaiyuan(),"购买牌匾",-1,userId);
				this.insertLogKaiyuan(0,sktBuyplaque.getKaiyuanFee(),39,sktBuyplaque1.getOrderNo(),account.getKaiyuan(),"购买牌匾的手续费和税率",-1,userId);
				account.setKaiyuan(account.getKaiyuan().subtract(totalKaiyuan));
				am.updateById(account);
			}else if (payType==6){//华宝货款
				AccountShop accountShop=new AccountShop();
				accountShop.setUserId(userId);
				EntityWrapper<AccountShop> ew=new EntityWrapper<AccountShop>(accountShop);
				AccountShop accountShop1 = accountShopService.selectOne(ew);
				BigDecimal totalKaiyuanTurnover=sktBuyplaque1.getKaiyuan().add(sktBuyplaque1.getKaiyuanFee());
				if (totalKaiyuanTurnover.compareTo(accountShop1.getKaiyuanTurnover())==1){
					json.put("code","00");
					json.put("msg","您的账户华宝货款余额不足，无法购买");
					return json;
				}
				this.insertLogKaiYuanTurnover(38,0,userId,sktBuyplaque1.getOrderNo(),accountShop1.getKaiyuanTurnover(),-1,sktBuyplaque.getKaiyuan(),"购买牌匾");
				this.insertLogKaiYuanTurnover(39,0,userId,sktBuyplaque1.getOrderNo(),accountShop1.getKaiyuanTurnover(),-1,sktBuyplaque.getKaiyuanFee(),"购买牌匾的手续费和税率");
				accountShop1.setKaiyuanTurnover(accountShop1.getKaiyuanTurnover().subtract(sktBuyplaque.getKaiyuan()).subtract(sktBuyplaque.getKaiyuanFee()));
				accountShopService.updateById(accountShop1);
			}
//			else if (payType==5){
//				if(sktBuyplaque.getKaiyuan().compareTo(BigDecimal.ZERO)==1){
//
//					this.insertLogKaiyuan(0,sktBuyplaque.getKaiyuan(),38,sktBuyplaque1.getOrderNo(),account.getKaiyuan(),"购买牌匾",-1,userId);
//					this.insertLogKaiyuan(0,sktBuyplaque.getKaiyuanFee(),39,sktBuyplaque1.getOrderNo(),account.getKaiyuan(),"购买牌匾的手续费和税率",-1,userId);
//					account.setKaiyuan(account.getKaiyuan().subtract(sktBuyplaque.getKaiyuan()).subtract(sktBuyplaque.getKaiyuanFee()));
//					am.updateById(account);
//				}
//				if (sktBuyplaque.getCash().compareTo(BigDecimal.ZERO)==1){
//					this.insertLogCash(-1,0,userId,sktBuyplaque1.getOrderNo(),account.getCash(),"购买牌匾",38,sktBuyplaque.getCash());
//					account.setCash(account.getCash().subtract(sktBuyplaque.getCash()));
//					am.updateById(account);
//				}
//
//			}
			json.put("code","01");
			json.put("msg","成功");
			return json;
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			json.put("code","00");
			json.put("msg","出错了");
			return json;
		}
	}

	//购买库存积分记录自动购买
	public Integer insertStockScore(String orderNo,Integer userId,Integer payType,BigDecimal totalMoney,BigDecimal realMoney,
								 BigDecimal cash,BigDecimal kaiyuan,BigDecimal kaiyuanFee,BigDecimal score,String orderRemarks){
		SktOrdersStockscore sktOrdersStockscore = new SktOrdersStockscore();
		// 生成订单号
		sktOrdersStockscore.setOrderNo(orderNo);
		sktOrdersStockscore.setUserId(userId);
		sktOrdersStockscore.setPayType(payType);
		sktOrdersStockscore.setTotalMoney(totalMoney);
		sktOrdersStockscore.setRealMoney(realMoney);
		sktOrdersStockscore.setCash(cash);
		sktOrdersStockscore.setKaiyuan(kaiyuan);
		sktOrdersStockscore.setKaiyuanFee(kaiyuanFee);
		sktOrdersStockscore.setScore(score);
		sktOrdersStockscore.setOrderRemarks(orderRemarks);
		sktOrdersStockscore.setCreateTime(new Date());
		sktOrdersStockscore.setCheckTime(new Date());
		sktOrdersStockscore.setOrderStatus(3);
		Integer insert = sktOrdersStockscoreMapper.insert(sktOrdersStockscore);

		return insert;
	}

	//购买库存积分记录
	public Integer insertStockScores(String orderNo,Integer userId,Integer payType,BigDecimal totalMoney,BigDecimal realMoney,
									BigDecimal cash,BigDecimal kaiyuan,BigDecimal kaiyuanFee,BigDecimal score,String orderRemarks){
		SktOrdersStockscore sktOrdersStockscore = new SktOrdersStockscore();
		// 生成订单号
		sktOrdersStockscore.setOrderNo(orderNo);
		sktOrdersStockscore.setUserId(userId);
		sktOrdersStockscore.setPayType(payType);
		sktOrdersStockscore.setTotalMoney(totalMoney);
		sktOrdersStockscore.setRealMoney(realMoney);
		sktOrdersStockscore.setCash(cash);
		sktOrdersStockscore.setKaiyuan(kaiyuan);
		sktOrdersStockscore.setKaiyuanFee(kaiyuanFee);
		sktOrdersStockscore.setScore(score);
		sktOrdersStockscore.setOrderRemarks(orderRemarks);
		sktOrdersStockscore.setCreateTime(new Date());
		sktOrdersStockscore.setCheckTime(new Date());
		sktOrdersStockscore.setOrderStatus(3);
		Integer insert = sktOrdersStockscoreMapper.insert(sktOrdersStockscore);

		return insert;
	}

	/**
	 * 赠送积分
	 * @param firstNum
	 * @param shopId
	 * @param userId
	 * @param orderStatus
	 * @param orderType
	 * @param payType
	 * @param totalMoney
	 * @param realMoney
	 * @param cash
	 * @param kaiyuan
	 * @param kaiyuanFee
	 * @param scoreRatio
	 * @param score
	 * @param orderRemarks
	 * @return
	 */
	public SktOrdersStores insertOrdersStores(String firstNum,Integer shopId ,Integer userId,Integer orderStatus,Integer orderType,Integer payType,BigDecimal totalMoney,BigDecimal realMoney,
									  BigDecimal cash,BigDecimal kaiyuan, BigDecimal kaiyuanFee,Integer scoreRatio,BigDecimal score,String orderRemarks){
		SktOrdersStores sktOrdersStores =new SktOrdersStores();
		sktOrdersStores.setOrderNo(StringUtils.getOrderIdByTime(firstNum));
		sktOrdersStores.setShopId(shopId);
		sktOrdersStores.setUserId(userId);
		sktOrdersStores.setOrderStatus(orderStatus);
		sktOrdersStores.setOrderType(orderType);
		sktOrdersStores.setPayType(payType);
		sktOrdersStores.setTotalMoney(totalMoney);
		sktOrdersStores.setRealMoney(realMoney);
		sktOrdersStores.setCash(cash);
		sktOrdersStores.setKaiyuan(kaiyuan);
		sktOrdersStores.setKaiyuanFee(kaiyuanFee);
		sktOrdersStores.setScoreRatio(scoreRatio);
		sktOrdersStores.setScore(score);
		sktOrdersStores.setOrderRemarks(orderRemarks);
		sktOrdersStores.setCreateTime(new Date());
		sktOrdersStores.setCheckTime(new Date());
		sktOrdersStores.setDataFlag(1);
		return sktOrdersStores;
	//	return  sktOrdersStoresService.insert(sktOrdersStores);
	}
	/**********************************app******************************************************/
    /**
     *  付款提交后输入交易密码
     * @param userPhone
     * @param payMoney
     * @param scoreRatio
     * @param payPwd
     * @param payType
     * @param userId
     * @return
     */
	@Override
	@Transactional
	public JSONObject personPay( String userPhone , BigDecimal payMoney,  Integer scoreRatio ,
											  String payPwd,  Integer payType,Integer userId){
		JSONObject json = new JSONObject();
		json.put("code","00");
		json.put("msg","该功能维护中");
		return  json;
//        SktOrdersStores sktOrdersStores=new SktOrdersStores();
//		Map<String, Object> map =new HashMap<>();
//		BigDecimal sendScore=payMoney.multiply(new BigDecimal(scoreRatio));//赠送积分
//        //付款人信息
//        Users saleUser=usersService.selectById(userId);
//		Users user =new Users();
//		user.setUserPhone(userPhone);
//		EntityWrapper<Users> entityWrapper=new EntityWrapper<Users>(user);
//		Users usersShop = usersService.selectOne(entityWrapper);//收款人
//		int userType=usersShop.getUserType();
//        SktShops sktShops=new SktShops();
//        sktShops.setUserId(usersShop.getUserId());
//        EntityWrapper<SktShops> ewp=new EntityWrapper<SktShops>(sktShops);
//        SktShops sktShops1 = sktShopsService.selectOne(ewp);
//        if (sktShops1==null){
//			json.put("code","00");
//			json.put("msg","收款人不是商家，不能收款");
//			return  json;
//		}
//		Account shopAccount=new Account();
//		shopAccount.setUserId(usersShop.getUserId());
//		EntityWrapper<Account> ewper=new  EntityWrapper<Account>(shopAccount);
//		Account shopAccount2 = this.selectOne(ewper); //商家的个人账户
//		AccountShop accountShop=new AccountShop();
//		accountShop.setUserId(usersShop.getUserId());
//		EntityWrapper<AccountShop> ewperAccountShop=new  EntityWrapper<AccountShop>(accountShop);
//		AccountShop accountShop1 = accountShopService.selectOne(ewperAccountShop);//商家账户表
//		if (sendScore.compareTo(accountShop1.getStockScore())==1){
//			json.put("code","00");
//			json.put("msg","商家库存积分不足以支付本次操作");
//			return  json;
//		}
//		JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);//付款密码校验
//		if ("00".equals(jsonObject)){
//			return jsonObject;
//		}else{
//			try{
//				Account account=new Account();
//				account.setUserId(userId);
//				EntityWrapper<Account> ew =new EntityWrapper<Account>(account);
//				Account account1 = this.selectOne(ew);
//
//                if (payType==3){  //华宝消费
//                    SktSysConfigs taxRatio = sktSysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");//综合服务费
//                    String  taxRatios=taxRatio.getFieldValue();//综合服务费用
//                    BigDecimal ratio=new BigDecimal(taxRatios);
//                    SktSysConfigs kaiyuanFees = sktSysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");//华宝支付手续费
//                    String  kaiyuanFee=kaiyuanFees.getFieldValue();//华宝支付手续费
//                    BigDecimal kaiyuanF=new BigDecimal(kaiyuanFee);
//                    BigDecimal kaiyuanZongFe=kaiyuanF.add(ratio).divide(new BigDecimal(100)).setScale(3,BigDecimal.ROUND_HALF_UP);
//					BigDecimal huabaoFee=payMoney.multiply(new BigDecimal(100)).multiply(kaiyuanZongFe);
//              		BigDecimal totalHuabao=huabaoFee.add(payMoney.multiply(new BigDecimal(100)));
//					BigDecimal huabao=account1.getKaiyuan();
//					if (totalHuabao.compareTo(huabao)==1) {
//						json.put("code", "00");
//						json.put("msg", "账户华宝余额不足以支付本次账单和费率");
//						return json;
//					}
//
//					//生成线下订单
//					 sktOrdersStores = this.insertOrdersStores("1", sktShops1.getShopId(), userId, 3, 1, 1, payMoney,BigDecimal.ZERO,  BigDecimal.ZERO,sendScore,  huabaoFee, scoreRatio, payMoney.multiply(new BigDecimal(scoreRatio)), "当面付款下单");
//					sktOrdersStoresService.insert(sktOrdersStores);
//
//					if(userType==0){
//						//5.商家待发华宝货款
//						this.insertLogKaiyuanFreeze(userId,sktOrdersStores.getKaiyuan(),1,sktOrdersStores.getOrderNo(),accountShop1.getFreezeKaiyuan(),"线下商城营业额获得",2,usersShop.getUserId());
//						accountShop1.setFreezeKaiyuan(accountShop1.getFreezeKaiyuan().add(sendScore));
//					}else{
//						//6.商家华宝货款流水
//						this.hbTurnover(5, userId, usersShop.getUserId(), sktOrdersStores.getOrderNo(), 1, sendScore, "线下商城营业额获得");
//						accountShop1.setKaiyuanTurnover(accountShop1.getKaiyuanTurnover().add( sendScore));//门店获得开元宝支付的营业额
//						accountShop1.setTotalKaiyuanTurnover(accountShop1.getTotalKaiyuanTurnover().add(sendScore));//门店累计获得开元宝支付的营业额
//					}
//					//商家库存积分流水
//					this.insertLogStockScore(4,usersShop.getUserId(),usersShop.getUserId(),sktOrdersStores.getOrderNo(),accountShop1.getStockScore(),-1,sendScore,"线下订单发放库存积分");
//					accountShop1.setStockScore(accountShop1.getStockScore().subtract(sendScore));
//					accountShop1.setOfflineTurnover(accountShop1.getOfflineTurnover().add(payMoney));
//					accountShop1.setTotalGiveStockScore(accountShop1.getTotalGiveStockScore().add(sendScore));//累计分发库存积分
//					accountShopService.updateById(accountShop1);//修改商家商城账户
//					//买家积分流水
//					this.insertLogScore(usersShop.getUserId(),2,sktOrdersStores.getOrderNo(),account1.getScore(),"当面付获得积分",sendScore,1,userId);
//					// 华宝消费记录
//					this.insertLogKaiyuan(userId, sendScore, -1, sktOrdersStores.getOrderNo(), account1.getKaiyuan(), "线下商城消费支出", 37,usersShop.getUserId() );
//					//华宝消费手续费记录
//					this.insertLogKaiyuan(userId , huabaoFee, -1, sktOrdersStores.getOrderNo(), account1.getKaiyuan(), "消费的手续费和税率的支出", 32,usersShop.getUserId() );
//					account1.setKaiyuan(account1.getKaiyuan().subtract(sendScore).subtract(huabaoFee));
//					account1.setScore(account1.getScore().add(sendScore));
//					account1.setTotalScore(account1.getTotalScore().add(sendScore));
//					am.updateById(account1);//修改买家账户
//                    json.put("orderNo",sktOrdersStores.getOrderNo());
//					json.put("payMoney",payMoney);
//					json.put("createTime",sktOrdersStores.getCreateTime());
//                }else if (payType==2){ //现金消费
//					BigDecimal cash=account1.getCash();
//					if (payMoney.compareTo(cash)==1){
//						json.put("code", "00");
//						json.put("msg", "账户余额不足以支付本次账单");
//						return json;
//					}
//					//生成线下订单
//					 sktOrdersStores = this.insertOrdersStores("1", sktShops1.getShopId(), userId, 3, 1, 1, payMoney, BigDecimal.ZERO, payMoney, BigDecimal.ZERO, BigDecimal.ZERO, scoreRatio, payMoney.multiply(new BigDecimal(scoreRatio)), "当面付款下单");
//					sktOrdersStoresService.insert(sktOrdersStores);
////					this.insertLogCash(1,userId,usersShop.getUserId(),sktOrdersStores.getOrderNo(),account1.getCash(),"当面付获得",37,payMoney);
//					if(userType==0){
//						freezeCashToFormal(3,userId,usersShop.getUserId(),sktOrdersStores.getOrderNo(),shopAccount2.getFreezeCash(),1,payMoney,"当面付获得");
//						shopAccount2.setFreezeCash(shopAccount2.getFreezeCash().add(payMoney));
//					}else{
//						insertLogCash(1,userId,usersShop.getUserId(),sktOrdersStores.getOrderNo(),shopAccount2.getCash(),"当面付获得",9,payMoney);
//						shopAccount2.setCash(shopAccount2.getCash().add(payMoney));
//						shopAccount2.setTotalCash(shopAccount2.getTotalCash().add(payMoney));
//					}
//					this.updateById(shopAccount2);//修改商家个人账户
//					//买家积分流水
//					this.insertLogScore(usersShop.getUserId(),2,sktOrdersStores.getOrderNo(),account1.getScore(),"当面付获得积分",sendScore,1,userId);
//					//买家现金流水
//					this.insertLogCash(-1,usersShop.getUserId(),userId,sktOrdersStores.getOrderNo(),account1.getCash(),"当面付消费",37,payMoney);
//					account1.setCash(account1.getCash().subtract(payMoney));
//					account1.setScore(account1.getScore().add(sendScore));
//					account1.setTotalScore(account1.getTotalScore().add(sendScore));
//					am.updateById(account1);//修改买家账户
//				//商家库存积分流水
//					this.insertLogStockScore(4,usersShop.getUserId(),usersShop.getUserId(),sktOrdersStores.getOrderNo(),accountShop1.getStockScore(),-1,sendScore,"线下订单发放库存积分");
//					accountShop1.setStockScore(accountShop1.getStockScore().subtract(sendScore));
//					accountShop1.setOfflineTurnover(accountShop1.getOfflineTurnover().add(payMoney));
//					accountShop1.setTotalGiveStockScore(accountShop1.getTotalGiveStockScore().add(sendScore));//累计分发库存积分
//					accountShopService.updateById(accountShop1);//修改商家商城账户
//					json.put("orderNo",sktOrdersStores.getOrderNo());
//					json.put("payMoney",payMoney);
//					json.put("createTime",sktOrdersStores.getCreateTime());
//				}
//                //是否开启销售奖
//                SktSysConfigs sysConfigsisXiaoshou = sysConfigsMapper.selectSysConfigsByFieldCode("isXiaoshou");
//                String isXiaoshouValue = sysConfigsisXiaoshou.getFieldValue();
//                if("1".equals(isXiaoshouValue)){
//                    //8卖家推荐人销售奖
//                    if(usersShop.getInviteId()!=0){
//                        this.marketAward(usersShop.getInviteId(),sendScore, userId,sktOrdersStores.getOrderNo());
//                    }
//                }
//                //是否开启销费奖
//                SktSysConfigs sysConfigsisXiaofei = sysConfigsMapper.selectSysConfigsByFieldCode("isXiaofei");
//                String isXiaofeiValue = sysConfigsisXiaofei.getFieldValue();
//                if("1".equals(isXiaofeiValue)){
//                    //7.买家推荐人消费奖励
//
//                    if(saleUser.getInviteId()!=0){
//                        this.saleAward(saleUser.getInviteId(), sendScore,userId,sktOrdersStores.getOrderNo());
//                    }
//                }
//                //是否开启特别奖励
//                SktSysConfigs sysConfigsisOrNoFenrun = sysConfigsMapper.selectSysConfigsByFieldCode("isOrNoFenrun");
//                String isOrNoFenrun = sysConfigsisOrNoFenrun.getFieldValue();
//                if ("1".equals(isOrNoFenrun)){
//                    //9.特别奖励
//                    //9.1 消费特别奖
//                    List<Integer> ids = usersService.getIds(userId);
//                    if(ids!=null && ids.size()>0){
//                        SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("consumeProfit");
//                        String fieldValue = sysConfig.getFieldValue();
//                        BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
//                        specialAward(ids,percent, sendScore,1,saleUser.getInviteId(),sktOrdersStores.getOrderNo());
//                    }
//                    //9.2销售特别奖
//                    Integer inviteId = usersShop.getInviteId();
//                    List<Integer> idss = usersService.getIds(usersShop.getUserId());
//                    if(idss!=null && idss.size()>0){
//                        SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("turnoverProfit");
//                        String fieldValue = sysConfig.getFieldValue();
//                        BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
//                        specialAward(idss,percent, sendScore,2,inviteId,sktOrdersStores.getOrderNo());
//                    }
//                }
//				json.put("code","01");
//				return  json;
//			}catch (Exception e){
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//				json.put("code","00");
//				json.put("msg","系统错误");
//				return  json;
//			}
//		}

	}
	public  int insertLogOrders(Integer orderId,Integer orderStatus,String logContent,Integer logUserId,Integer logType){
        LogOrders logOrders=new LogOrders();
        logOrders.setOrderId(orderId);
        logOrders.setOrderStatus(orderStatus);
        logOrders.setLogContent(logContent);;
        logOrders.setLogUserId(logUserId);
        logOrders.setLogType(logType);
        logOrders.setLogTime(new Date());
          return   logOrdersMapper.insert(logOrders);
    }

	/**
	 * 现金和华宝支付 购物券支付
	 * @param orderIdList 订单集合
	 * @param userId  用户id
	 * @param payType 支付类型
	 * @param payMoney  支付现金
	 * @param payKaiyuan  支付华宝或者华宝货款
	 * @param feeKaiyuan 支付华宝或者华宝货款手续费
	 * @return
	 */
	@Transactional
	@Override
	public  Map<String,Object> payment(List<String> orderIdList,Integer userId,Integer payType,
									   BigDecimal payMoney,BigDecimal payKaiyuan,BigDecimal feeKaiyuan,BigDecimal payShopping,
									   String  thirdNo,Integer thirdType,String payName){
		Map<String,Object> result =new HashMap<>();
		try {
			if (orderIdList != null && orderIdList.size() > 0) {
				String oId = orderIdList.get(0);
				SktOrders sktOrder=ordersMapper.selectById(oId);
				String orderunique=sktOrder.getOrderunique();
				//根据userId查账户
				Account account=am.selectAccountByuserId(userId);
				for (String orderId : orderIdList) {
					SktOrders sktOrders = ordersMapper.selectById(orderId);
					if (sktOrders.getOrderStatus() == -1) {
						result.put("code", "00");
						result.put("msg", "订单已过期");
						return result;
					}

				}
//				if (account.getCash().compareTo(payMoney)==-1){
//					result.put("code", "00");
//					result.put("msg", "账户现金余额不足");
//					return result;
//				}


				BigDecimal totalKuanyuan=payKaiyuan.add(feeKaiyuan);
				//现金+华宝
				if (payType == 7) {
					if (account.getKaiyuan().compareTo(totalKuanyuan)==-1){
						result.put("code", "00");
						result.put("msg", "账户华宝余额不足");
						return result;
					}
				}
				//现金+华宝货款
				if (payType == 8) {
					if (account.getKaiyuan().compareTo(totalKuanyuan)==-1){
						result.put("code", "00");
						result.put("msg", "账户华宝余额不足");
						return result;
					}
					AccountShop userAccountShop = new AccountShop();
					userAccountShop.setUserId(userId);
					EntityWrapper<AccountShop> entityWrapper = new EntityWrapper<AccountShop>(userAccountShop);
					AccountShop userAccountShop1 = accountShopService.selectOne(entityWrapper);
					if (userAccountShop1==null){
						result.put("code", "00");
						result.put("msg", "没有商家账户无法用华宝货款支付");
						return result;
					}
					BigDecimal kaiyuanTurnover = userAccountShop1.getKaiyuanTurnover();
					if (totalKuanyuan.compareTo(kaiyuanTurnover) == 1) {
						result.put("code", "00");
						result.put("msg", "账户华货款宝余额不足");
						return result;
					}
				}
				if (payType==9){
					if (account.getShoppingMoney().compareTo(payShopping)==-1){
						result.put("code", "00");
						result.put("msg", "账户购物券余额不足");
						return result;
					}
				}
				if (payType==10){
					if (payShopping.compareTo(account.getShoppingMoney())==1){
						result.put("code", "00");
						result.put("msg", "账户购物券余额不足");
						return result;
					}

				}

				for (String orderId:orderIdList){
					SktOrders sktOrders = ordersMapper.selectById(orderId);
					SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String paymentTimes = sdft.format(new Date());
					Date paymentTime=sdft.parse(paymentTimes);
					BigDecimal  cash = account.getCash();
					BigDecimal kaiyuan = account.getKaiyuan();
					Integer shopId = sktOrders.getShopId();
					SktShops sktShops = sktShopsService.selectById(shopId);
					Map<String,Object> map2 = new HashMap<String,Object>();
					if(sktShops.getCompanyType() == 0) {
						//个体户每日限额
						SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("gthMRXE");
						String gthMRXE = sktSysConfigs2.getFieldValue();
						Map<String,Object> map3 = new HashMap<String,Object>();
						map3.put("shopId",shopId);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String today = sdf.format(new Date());
						map3.put("today",today);
						//查询商家的今日营业额
						BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map3);
						if(todayTurnover != null){
							if(todayTurnover.add(sktOrders.getGoodsMoney()).compareTo(new BigDecimal(gthMRXE)) == 1){
								map2.put("msg","对不起商家"+sktShops.getShopName()+"今日销售限额已达上限！");
								map2.put("code","00");
								return map2;
							}
						}
					}
					if(sktShops.getCompanyType() == 1){
						//公司每日限额
						SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("qyMRXE");
						String qyMRXE = sktSysConfigs2.getFieldValue();
						Map<String,Object> map3 = new HashMap<String,Object>();
						map3.put("shopId",shopId);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String today = sdf.format(new Date());
						map3.put("today",today);
						//查询商家的今日营业额
						BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map3);
						if(todayTurnover != null){
							if(todayTurnover.add(sktOrders.getGoodsMoney()).compareTo(new BigDecimal(qyMRXE)) == 1){
								map2.put("msg","对不起商家"+sktShops.getShopName()+"今日销售限额已达上限！");
								map2.put("code","00");
								return map2;
							}
						}
					}
					Integer notPayCountShop = sktOrdersStoresMapper.appFindNotPayOrders(map2);
					if(notPayCountShop!=null){
						if(notPayCountShop >= 2){
							map2.put("msg","对不起，您今日在本店铺未支付订单已达上线（2单），不能在此店铺下单了！");
							map2.put("code","00");
							return map2;
						}
					}

					//查询用户今天所有未支付订单
					map2.put("shopId","");
					Integer notPayCountAll = sktOrdersStoresMapper.appFindNotPayOrders(map2);
					if(notPayCountAll!=null){
						if(notPayCountShop >= 5){
							map2.put("msg","对不起，您今日未支付订单已达上线（5单），不能再下单了！");
							map2.put("code","00");
							return map2;
						}
					}
					AccountShop accountShop = accountShopMapper.selectByShopId(shopId);
					List<SktOrderGoods> list = ordersMapper.getOrderGoodsByOrderId(Integer.parseInt(orderId));
					SktOrdersExtension ordersExtension=new SktOrdersExtension();//订单扩展表
					ordersExtension.setOrderId(sktOrders.getOrderId().toString());//订单扩展表
					Map<String, Object> afterSevenWorkDay = getAfterSevenWorkDay(7);
					//String  StrAutoTakeTime=afterSevenWorkDay.get("endDay").toString();
					String  endDays=afterSevenWorkDay.get("endDay").toString().substring(0,10);
					SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
					String time = format.format(new Date());
					String  newTime=endDays+" "+time;
					SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
					Date newDate  = sdf.parse(newTime );
					ordersExtension.setAutoTakeTime(newDate); //应自动收货时间
					ordersExtension.setIsAutoTake(0);//是否自动收货 0否；1是 2已手动收货
					ordersExtension.setIsSettle(1);//批处理标示符：1未处理 2已处理 9处理中
					BigDecimal sumScore=BigDecimal.ZERO;
					if(payType==2){//现金账户
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsStock){
								result.put("code","00");
								result.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  result;
							}
							sumScore=sumScore.add(orderGoodsScore);
						}
						//	bigSumScore=bigSumScore.add(sumScore);
						sktOrders.setIsPay(1);
						sktOrders.setPayType(2);
						sktOrders.setOrderStatus(0);
						sktOrders.setCash(tatolMoney);
						sktOrders.setTotalMoney(tatolMoney);
						sktOrders.setPaymentTime(new Date());
						ordersExtension.setScore(sumScore);//订单扩展表
						ordersExtension.setScoreFlag(1);//库存积分标识：1店铺库存积分充足 2库存不足扣营业额购买库存积分
						//生成现金流水
						this.insertLogCash(-1, 0, userId, sktOrders.getOrderNo(), cash, "线上商城消费", 33,tatolMoney );
						ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
						account.setCash(account.getCash().subtract(tatolMoney));
						am.updateById(account);//用户账户变化
						ordersMapper.updateById(sktOrders);
					}
					if(payType==7){//现金+华宝支付

						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsNum){
								result.put("code","00");
								result.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  result;
							}
							goods.setGoodsStock(goodsStock-goodsNum);
							goodsService.updateById(goods);
							if (goods.getIsSpec()==1){
								String goodsSpecId = orderGoods.getGoodsSpecId();
								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
								if (goodsSpecs!=null){
									Integer specStock = goodsSpecs.getSpecStock();//规格库存
									if (specStock<goodsNum){
										result.put("code","00");
										result.put("msg","商品"+goods.getGoodsName()+"库存不足");
										return  result;
									}else{
										goodsSpecs.setSpecStock(specStock-goodsNum);
										goodsSpecsService.updateById(goodsSpecs);
									}
								}
							}
							//    kaiyuanPay=kaiyuanPay.add(goods.getPayKaiyuan());
						}
						//订单所需华宝
						BigDecimal kaiyuanPay=sktOrders.getKaiyuan();
						//查询华宝支付手续费
						SktSysConfigs kaiyuanFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");
						BigDecimal huaBaoFee = new BigDecimal(kaiyuanFee.getFieldValue());
						//综合服务费
						SktSysConfigs taxRatio = sysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");
						BigDecimal taxRatio2 = new BigDecimal(taxRatio.getFieldValue());
						//订单所需华宝手续费
						BigDecimal  feeKaiyuanPay = kaiyuanPay.multiply(huaBaoFee).add(kaiyuanPay.multiply(taxRatio2)).multiply(new BigDecimal(0.01));
						//订单所需现金
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
						ordersExtension.setScoreFlag(1);
						//华宝消费手续费记录
						this.insertLogKaiyuan(0, feeKaiyuanPay, -1, sktOrders.getOrderNo(), account.getKaiyuan().subtract(kaiyuanPay), "消费的手续费和税率的支出", 32, account.getUserId());
						// 华宝消费记录
						this.insertLogKaiyuan(0, kaiyuanPay, -1, sktOrders.getOrderNo(), account.getKaiyuan(), "线上商城消费支出", 31, account.getUserId());
						//生成现金流水
						this.insertLogCash(-1, 0, userId, sktOrders.getOrderNo(), cash, "线上商城消费", 33,tatolMoney );

						sktOrders.setIsPay(1);
						sktOrders.setPayType(payType);
						//   sktOrders.setKaiyuan(kaiyuanPay);
						sktOrders.setKaiyuanFee(feeKaiyuanPay);
						sktOrders.setTotalMoney(tatolMoney);
						sktOrders.setOrderStatus(0);
						sktOrders.setPaymentTime(new Date());
						ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
						BigDecimal	toal=feeKaiyuanPay.add(kaiyuanPay);
						account.setKaiyuan(account.getKaiyuan().subtract(toal));
						account.setCash(cash.subtract(tatolMoney));
						am.updateById(account);//用户账户变化
						ordersMapper.updateById(sktOrders);
					}
					//现金+华宝货款支付
					if(payType==8){

						for (SktOrderGoods orderGoods:list) {
							BigDecimal orderGoodsScore = orderGoods.getScore();
							int goodsId = orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum = orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock < goodsStock) {
								result.put("code", "00");
								result.put("msg", "商品" + goods.getGoodsName() + "库存不足");
								return result;
							}
							goods.setGoodsStock(goodsStock-goodsNum);
							goodsService.updateById(goods);
							if (goods.getIsSpec()==1){
								String goodsSpecId = orderGoods.getGoodsSpecId();
								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
								if (goodsSpecs!=null){
									Integer specStock = goodsSpecs.getSpecStock();//规格库存
									if (specStock<goodsNum){
										result.put("code","00");
										result.put("msg","商品"+goods.getGoodsName()+"库存不足");
										return  result;
									}else{
										goodsSpecs.setSpecStock(specStock-goodsNum);
										goodsSpecsService.updateById(goodsSpecs);
									}
								}
							}
							//    kaiyuanTurnoverPay=kaiyuanTurnoverPay.add(goods.getPayKaiyuan());
						}
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
						BigDecimal kaiyuanTurnoverPay=sktOrders.getKaiyuan();
						//华宝货款手续费
						SktSysConfigs kaiyuanturnFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
						BigDecimal huaBaoTurnFee = new BigDecimal(kaiyuanturnFee.getFieldValue());
						BigDecimal  feekaiyuanTurnoverPay = kaiyuanTurnoverPay.multiply(huaBaoTurnFee).multiply(new BigDecimal(0.01));
						AccountShop   userAccountShop=new AccountShop();
						userAccountShop.setUserId(userId);
						EntityWrapper<AccountShop> entityWrapper=new EntityWrapper<AccountShop>(userAccountShop) ;
						AccountShop userAccountShop1 = accountShopService.selectOne(entityWrapper);
						BigDecimal  tatolKaiyuanTurnover=kaiyuanTurnoverPay.add(feekaiyuanTurnoverPay);
						ordersExtension.setScoreFlag(1);
						if(userAccountShop1!=null){
							// 华宝货款消费记录
							this.insertLogKaiYuanTurnover(32,0,userId,sktOrders.getOrderNo(),userAccountShop1.getKaiyuanTurnover().subtract(kaiyuanTurnoverPay),-1,feekaiyuanTurnoverPay,"消费的手续费和税率的支出");
							this.insertLogKaiYuanTurnover(31,0,userId,sktOrders.getOrderNo(),userAccountShop1.getKaiyuanTurnover(),-1,kaiyuanTurnoverPay,"线上商城消费支出");
							userAccountShop1.setKaiyuanTurnover(userAccountShop1.getKaiyuanTurnover().subtract(tatolKaiyuanTurnover));
							accountShopService.updateById(userAccountShop1);
						}
						//生成现金流水
						this.insertLogCash(-1, 0, userId, sktOrders.getOrderNo(), cash, "线上商城消费", 33,tatolMoney );
						account.setCash(cash.subtract(tatolMoney));
						this.updateById(account);//用户账户变化
						sktOrders.setIsPay(1);
						sktOrders.setPayType(payType);
						sktOrders.setKaiyuan(kaiyuanTurnoverPay);
						sktOrders.setKaiyuanFee(feekaiyuanTurnoverPay);
						sktOrders.setTotalMoney(tatolMoney);
						sktOrders.setOrderStatus(0);
						sktOrders.setPaymentTime(new Date());
						ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
						ordersMapper.updateById(sktOrders);
					}
					if(payType==9){//现金账户+优惠券
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
						//	BigDecimal totalShopping = sktOrders.getTotalShopping();
						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsStock){
								result.put("code","00");
								result.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  result;
							}
							goods.setGoodsStock(goodsStock-goodsNum);
							goodsService.updateById(goods);
							if (goods.getIsSpec()==1){
								String goodsSpecId = orderGoods.getGoodsSpecId();
								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
								if (goodsSpecs!=null){
									Integer specStock = goodsSpecs.getSpecStock();//规格库存
									if (specStock<goodsNum){
										result.put("code","00");
										result.put("msg","商品"+goods.getGoodsName()+"库存不足");
										return  result;
									}else{
										goodsSpecs.setSpecStock(specStock-goodsNum);
										goodsSpecsService.updateById(goodsSpecs);
									}
								}
							}
						}
						//	bigSumScore=bigSumScore.add(sumScore);
						sktOrders.setIsPay(1);
						sktOrders.setPayType(2);
						sktOrders.setOrderStatus(0);
						sktOrders.setCash(tatolMoney);
						sktOrders.setTotalMoney(tatolMoney);
						sktOrders.setPaymentTime(new Date());
						sktOrders.setTotalShopping(payShopping);
						ordersExtension.setScore(sumScore);//订单扩展表
						ordersExtension.setScoreFlag(1);//库存积分标识：1店铺库存积分充足 2库存不足扣营业额购买库存积分
						//生成现金流水
						this.insertLogCash(-1, 0, userId, sktOrders.getOrderNo(), cash, "线上商城消费", 33,tatolMoney );
						//生成优惠券流水
						Shopping shopping = this.getShopping(1, userId, sktOrders.getOrderNo(), payShopping, "商城购物消费",2, 2,-1);
						shoppingService.insert(shopping);
						ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
						account.setCash(account.getCash().subtract(tatolMoney));
						account.setShoppingMoney(account.getShoppingMoney().subtract(payShopping));
						am.updateById(account);//用户账户变化
						ordersMapper.updateById(sktOrders);
					}
					if(payType==10){//微信或支付宝+优惠券
						BigDecimal tatolMoney=sktOrders.getTotalMoney();
						//	BigDecimal totalShopping = sktOrders.getTotalShopping();
						for (SktOrderGoods orderGoods:list) {
							BigDecimal  orderGoodsScore=orderGoods.getScore();
							int goodsId=orderGoods.getGoodsId();
							Goods goods = goodsService.selectById(goodsId);
							int goodsNum=orderGoods.getGoodsNum();
							int goodsStock = goods.getGoodsStock();
							if (goodsStock<goodsNum){
								result.put("code","00");
								result.put("msg","商品"+goods.getGoodsName()+"库存不足");
								return  result;
							}
							goods.setGoodsStock(goodsStock-goodsNum);
							goodsService.updateById(goods);
							if (goods.getIsSpec()==1){
								String goodsSpecId = orderGoods.getGoodsSpecId();
								GoodsSpecs goodsSpecs = goodsSpecsService.selectById(goodsSpecId);
								if (goodsSpecs!=null){
									Integer specStock = goodsSpecs.getSpecStock();//规格库存
									if (specStock<goodsNum){
										result.put("code","00");
										result.put("msg","商品"+goods.getGoodsName()+"库存不足");
										return  result;
									}else{
										goodsSpecs.setSpecStock(specStock-goodsNum);
										goodsSpecsService.updateById(goodsSpecs);
									}
								}
							}
						}
						sktOrders.setIsPay(1);
						sktOrders.setPayType(10);
						sktOrders.setOrderStatus(4);
						sktOrders.setCash(tatolMoney);
						sktOrders.setTotalMoney(tatolMoney);
						sktOrders.setPaymentTime(new Date());
						sktOrders.setTotalShopping(payShopping);
						ordersExtension.setScore(sumScore);//订单扩展表
						ordersExtension.setScoreFlag(1);//库存积分标识：1店铺库存积分充足 2库存不足扣营业额购买库存积分
						//生成现金流水
//						this.insertLogCash(-1, 0, userId, sktOrders.getOrderNo(), cash, "线上商城消费", 33,tatolMoney );

						//生成优惠券流水
						Shopping shopping = this.getShopping(1, userId, sktOrders.getOrderNo(), payShopping, "商城购物消费", 2,2,-1);
						shoppingService.insert(shopping);
						ordersExtension.setScore(sumScore);
						SktOrdersExtensionMapper.insert(ordersExtension);
//						account.setCash(account.getCash().subtract(tatolMoney));
						account.setShoppingMoney(account.getShoppingMoney().subtract(payShopping));
						am.updateById(account);//用户账户变化
						ordersMapper.updateById(sktOrders);
					}
					List<Integer> usersIds=new ArrayList<Integer>();
					usersIds.add(accountShop.getUserId());
					//发送系统消息
					messagesService.addMessages(1,1,usersIds,"您有一笔订单【"+sktOrders.getOrderNo()+"】用户已支付，请尽快发货",null);
					//生成订单记录表
					this.insertLogOrders(sktOrders.getOrderId(),-2,"下单成功，等待用户支付",userId,0);
				}
				if(payType==10){
					//插入第三方流水
					if (thirdNo==null || "".equals(thirdNo)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						result.put("code", "00");
						result.put("msg", "请输入第三方订单号");
						return result;
					}

					SktOrderReview sktOrderReview1=new SktOrderReview();
					sktOrderReview1.setOutTradeNo(thirdNo);
					EntityWrapper<SktOrderReview> entityWrapper =new EntityWrapper<SktOrderReview>(sktOrderReview1);
					SktOrderReview sktOrderReview2 = sktOrderReviewService.selectOne(entityWrapper);
					if (sktOrderReview2!=null){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						result.put("code", "00");
						result.put("msg", "该订单号已经支付，请重新支付");
						return result;
					}
					SktOrderReview sktOrderReview3=new SktOrderReview();
					sktOrderReview3.setOrderunique(orderunique);
					EntityWrapper<SktOrderReview> wrapper =new EntityWrapper<SktOrderReview>(sktOrderReview3);
					SktOrderReview sktOrderReview4 = sktOrderReviewService.selectOne(wrapper);
					if (sktOrderReview4!=null){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						result.put("code", "00");
						result.put("msg", "该订单流水号已经支付，请重新支付");
						return result;
					}
					//插入校验表
					SktOrderReview sktOrderReview=this.getSktOrderReview(userId,orderunique,thirdNo,thirdType,payMoney,payShopping);
					sktOrderReviewService.insert(sktOrderReview);
				}
			}
			result.put("code", "01");
			result.put("msg", "下单成功");
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.put("code", "00");
			result.put("msg", "下单失败");
		}
		return result;
	}

	/**
	 * 确认收货
	 * @param orderIdList
	 * @return
	 */
	@Override
	@Transactional
    public Boolean enter(List<Integer> orderIdList){
        Map<String,Object> result=new HashMap<>();
        try{
            if(orderIdList!=null && orderIdList.size()>0){
                int userId=0;
                BigDecimal sumCash=new BigDecimal("0");//买家用户消费金额
                for (Integer orderId:orderIdList){
                    userId = ordersMapper.selectById(orderIdList.get(0)).getUserId();
                    SktOrders orders = ordersMapper.selectById(orderId);
                    BigDecimal cash=orders.getGoodsMoney();
                    sumCash=sumCash.add(cash);
                    BigDecimal kaiyuan=orders.getKaiyuan();
                    int shopId=orders.getShopId();
                    AccountShop accountShop = accountShopMapper.selectByShopId(shopId);
                    Account account=new Account();
                    account.setShopId(shopId);
                    EntityWrapper<Account> ewp=new EntityWrapper<Account>(account);
                    Account account1 = this.selectOne(ewp);//商家对应的个人账户
					Integer shopUserId=account1.getUserId();//商家对应的id
                    BigDecimal score=new BigDecimal("0");//订单获得积分
                    List<SktOrderGoods> list = ordersMapper.getOrderGoodsByOrderId(orderId);
                    if(list!=null&& list.size()>0){
                        for (SktOrderGoods orderGoods:list) {
                            BigDecimal  orderGoodsScore=orderGoods.getScore();
                            int goodsNum=orderGoods.getGoodsNum();
                            score=score.add(orderGoodsScore);
                            Goods goods = goodsMapper.selectById(orderGoods.getGoodsId());
                            goods.setSaleNum(goods.getSaleNum()+goodsNum);//商品销量增加
                            goodsMapper.updateById(goods);
                            //商品规格表销售量增加
                            GoodsSpecs goodsSpecs=new GoodsSpecs();
                            goodsSpecs.setGoodsId(orderGoods.getGoodsId());
                            EntityWrapper<GoodsSpecs> ew=new EntityWrapper<GoodsSpecs>(goodsSpecs);
                            GoodsSpecs goodsSpecs1 = goodsSpecsService.selectOne(ew);
                            if(goodsSpecs1!=null){
                                goodsSpecs1.setSaleNum(goodsSpecs1.getSaleNum()+goodsNum);
                                goodsSpecsService.updateById(goodsSpecs1);
                            }
                        }
                    }

                    SktOrdersExtension ordersExtension=new SktOrdersExtension();
                    ordersExtension.setOrderId(orderId.toString());
                    EntityWrapper<SktOrdersExtension> ew=new EntityWrapper<SktOrdersExtension>(ordersExtension);
                    SktOrdersExtension sktOrdersExtension = sktOrdersExtensionService.selectOne(ew);
                    Integer userSarketId=accountShop.getUserId();
                    Users userSarket = usersMapper.selectById(userSarketId);//获得商家对应的user
                    int userType=userSarket.getUserType();//得判断商家对应用户类型
                        //3.商家账户变更 现金，冻结积分  华宝
                        if(cash.compareTo(BigDecimal.ZERO)==1){
                            accountShop.setOnlineTurnover(accountShop.getOnlineTurnover().add(cash));//线上商城营业额
                        }
                        if(orders.getPayType()==2 ||orders.getPayType()==4){
                            if(userType==0){
                                freezeCashToFormal(2,0,userSarketId,orders.getOrderNo(),account1.getFreezeCash(),1,orders.getTotalMoney(),"线上商城营业额进入待发");
                                account1.setFreezeCash(account1.getFreezeCash().add(orders.getCash()));
                            }else{
                                insertLogCash(1,0,userSarketId,orders.getOrderNo(),account1.getCash(),"订单结算增加金额",3,orders.getTotalMoney());
                                account1.setCash(account1.getCash().add(orders.getTotalMoney()));
                                account1.setTotalCash(account1.getTotalCash().add(orders.getCash()));
                            }
                            am.updateById(account1);
                        }else if(orders.getPayType()==7){
                            if(userType==0){
                               //商家待发现金
								freezeCashToFormal(2,0,userSarketId,orders.getOrderNo(),account1.getFreezeCash(),1,orders.getTotalMoney(),"线上商城营业额进入待发");
								account1.setFreezeCash(account1.getFreezeCash().add(orders.getCash()));
								//5.商家待发华宝货款
								this.insertLogKaiyuanFreeze(0,kaiyuan,1,orders.getOrderNo(),accountShop.getFreezeKaiyuan(),"线上营业额获得",1,userSarketId);
                                accountShop.setFreezeKaiyuan(accountShop.getFreezeKaiyuan().add(kaiyuan));
                            }else{
                                //6.商家华宝货款流水
                                this.hbTurnover(1, 0, userSarketId, orders.getOrderNo(), 1, kaiyuan, "线上营业额获得");
                                accountShop.setKaiyuanTurnover(accountShop.getKaiyuanTurnover().add(kaiyuan));//门店获得开元宝支付的营业额
                                accountShop.setTotalKaiyuanTurnover(accountShop.getTotalKaiyuanTurnover().add(kaiyuan));//门店累计获得开元宝支付的营业额
								//商家现金
								insertLogCash(1,0,userSarketId,orders.getOrderNo(),account1.getCash(),"订单结算增加金额",3,orders.getTotalMoney());
								account1.setCash(account1.getCash().add(orders.getTotalMoney()));
								account1.setTotalCash(account1.getTotalCash().add(orders.getCash()));
                            }
                            am.updateById(account1);
                            accountShopMapper.updateById(accountShop);
                        }else if (orders.getPayType()==8){
                            if (userType==0){
								//商家待发现金
								freezeCashToFormal(2,0,userSarketId,orders.getOrderNo(),account1.getFreezeCash(),1,orders.getTotalMoney(),"线上商城营业额进入待发");
								account1.setFreezeCash(account1.getFreezeCash().add(orders.getCash()));
								//5.商家待发华宝货款
                                this.insertLogKaiyuanFreeze(0,kaiyuan,1,orders.getOrderNo(),accountShop.getFreezeKaiyuan(),"线上营业额获得",1,userSarketId);
                                accountShop.setFreezeKaiyuan(accountShop.getFreezeKaiyuan().add(kaiyuan));
                            }else{
								//商家现金
								insertLogCash(1,0,userSarketId,orders.getOrderNo(),account1.getCash(),"订单结算增加金额",3,orders.getTotalMoney());
								account1.setCash(account1.getCash().add(orders.getTotalMoney()));
								account1.setTotalCash(account1.getTotalCash().add(orders.getCash()));
                                this.insertLogKaiYuanTurnover(1,0,userSarketId,orders.getOrderNo(),accountShop.getKaiyuanTurnover(),1,orders.getKaiyuan(),"线上商城营业额获得");
                                accountShop.setKaiyuanTurnover(accountShop.getKaiyuanTurnover().add(orders.getKaiyuan()));
                                accountShop.setTotalKaiyuanTurnover(accountShop.getTotalKaiyuanTurnover().add(orders.getKaiyuan()));
                            }
							am.updateById(account1);
                            accountShopMapper.updateById(accountShop);
                        }else if (orders.getPayType()==9||orders.getPayType()==10){//优惠券+现金支付 或优惠券+第三方
							if (userType==0){
								//商家待发现金
								freezeCashToFormal(2,0,userSarketId,orders.getOrderNo(),account1.getFreezeCash(),1,orders.getTotalMoney(),"线上商城营业额进入待发");
								account1.setFreezeCash(account1.getFreezeCash().add(orders.getCash()));
							}else{
								//商家现金
								insertLogCash(1,0,userSarketId,orders.getOrderNo(),account1.getCash(),"订单结算增加金额",3,orders.getTotalMoney());
								account1.setCash(account1.getCash().add(orders.getTotalMoney()));
                                account1.setTotalCash(account1.getTotalCash().add(orders.getCash()));
							}
							//商家优惠券流水
							Shopping shopping = this.getShopping(3, shopUserId, orders.getOrderNo(), orders.getTotalShopping(), "商城销售获得", 1,2, 1);
							shoppingService.insert(shopping);
							accountShop.setTotalShopping(accountShop.getTotalShopping().add(orders.getTotalShopping()));
							am.updateById(account1);
							accountShopMapper.updateById(accountShop);
						}

                        sktOrdersExtension.setIsAutoTake(2);
                        sktOrdersExtension.setSettleTime(new Date());
                        sktOrdersExtension.setIsSettle(2);
                        sktOrdersExtension.setRealSettleTime(new Date());
                        sktOrdersExtensionService.updateById(sktOrdersExtension);
                        Account account2=am.selectAccountByuserId(userId);
                        //2.买家账户表修改
                        account2.setOnlineExpenditure(account2.getOnlineExpenditure().add(sumCash));
                        am.updateById(account2);

                    orders.setIsClosed(1);							//订单结束
                    orders.setBatFlag(2);                  			//批处理标示符：1未处理 2已处理 9处理中
                    orders.setOrderStatus(2);                     // 用户确认收货
                    orders.setReceiveTime(new Date());                  // 收货时间
                    ordersMapper.updateById(orders);
                    List<Integer> usersIds=new ArrayList<Integer>();
                    usersIds.add(accountShop.getUserId());
                    //发送系统消息
                    messagesService.addMessages(1,1,usersIds,"订单【"+orders.getOrderNo()+"】用户已确认收货",null);
                    //生成订单记录表
                    this.insertLogOrders(orderId,2,"用户已收货",userId,0);
                }

            }
            return true;
        } catch (Exception e) {
        	e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

	/**
	 *
	 * @param userPhone  用户手机号
	 * @param type 用户身份 1会员 2代理
	 * @param money 金额
	 * @param sceneType 购物券使用场景 1通用 2线上 3线下 4无人超市
	 * @return
	 */
    //修改账户优惠券
	@Override
	@Transactional
	public Map<String, Object> addShopping(String userPhone,Integer type,BigDecimal money,Integer sceneType){
		Map<String, Object> resultMap=new HashMap<>();
		try{
			Map<String, Object> map=new HashMap<>();
			map.put("userPhone",userPhone);
			if (type==1){
				//根据手机号查询用户账户
				Account account = am.selectAccountByUserPhone(map);
				if (account==null){
					resultMap.put("code","00");
					resultMap.put("msg","此手机号在商城没有注册");
					return resultMap;
				}
				Integer dataId=account.getUserId();
				//生成流水
				String orderNo = StringUtils.getOrderIdByTime("MC");
				Shopping shopping = getShopping(type, dataId, orderNo, money, "猫币APP转换获得",1, sceneType,1);
				shoppingService.insert(shopping);
				//修改账户表
				account.setShoppingMoney(account.getShoppingMoney().add(money));
				this.updateById(account);

			}

			if (type==2){
				//根据手机号查询用户账户
				SktAgentsAccount sktAgentsAccount = agentsAccountMapper.selectAgentAccountByPhone(map);
				if (sktAgentsAccount==null){
					resultMap.put("code","00");
					resultMap.put("msg","此手机号在商城没有注册代理");
					return resultMap;
				}
				Integer dataId=sktAgentsAccount.getAgentId();
				//生成流水
				Shopping shopping = getShopping(type, dataId, "M", money, "猫币APP转换获得", 1,sceneType,1);
				shoppingService.insert(shopping);
				//修改账户表
				sktAgentsAccount.setShoppingMoney(sktAgentsAccount.getShoppingMoney().add(money));
				agentsAccountMapper.updateById(sktAgentsAccount);

			}
			resultMap.put("code","01");
			resultMap.put("msg","成功");
			return resultMap;
		}catch (Exception e){
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultMap.put("code","00");
			resultMap.put("msg","失败");
			return resultMap;

		}
	}

	/**生成优惠券流水
	 *
	 * @param type  用户身份 1会员 2代理
	 * @param dataId  目标用户ID
	 * @param money  金额
	 * @param remark  备注
	 * @param sceneType  购物券使用场景 1通用 2线上 3线下 4无人超市
	 * @param  shoppingType 流水标志 -1减少 1增加

	 * @return
	 */
	//优惠券流水
	public Shopping getShopping(Integer type,Integer dataId,String orderNo,BigDecimal money,String remark,Integer status, Integer sceneType,Integer shoppingType
	){
		Shopping shopping=new Shopping();
		shopping.setType(type);
		shopping.setDataId(dataId);
//		String orderNo = StringUtils.getOrderIdByTime(first);
		shopping.setOrderNo(orderNo);
		shopping.setMoney(money);
		shopping.setRemark(remark);
		shopping.setDataFlag(1);
		Date date=new Date();
		shopping.setCreateTime(date);
		Calendar calendar = new GregorianCalendar();
		Date overdueTime = new Date();
		calendar.setTime(overdueTime);
		calendar.add(calendar.YEAR, 1);//把日期往后增加一年.整数往后推,负数往前移动
		overdueTime=calendar.getTime();   //这个时间就是日期往后推一天的结果
		shopping.setOverdueTime(overdueTime);
		shopping.setStatus(status);
		shopping.setSceneType(sceneType);
		shopping.setShoppingType(shoppingType);
		return   shopping;

	}
@Override
	public  Map<String,Object> compareShopping(BigDecimal shopping,String userIds){
		Map<String,Object> map=new HashMap<>();
		if(userIds==null || !"".equals(userIds)){
			map.put("code","00");
			map.put("msg","您未登录请重新登录");
			return map;
		}
		Integer userId=Integer.parseInt(userIds);
		Account account =new Account();
		account.setUserId(userId);
		EntityWrapper<Account>  entityWrapper=new EntityWrapper<Account>(account);
		Account account1 = this.selectOne(entityWrapper);
		BigDecimal shoppingMoney = account1.getShoppingMoney();
		if (shoppingMoney.compareTo(shopping)==-1){
			map.put("code","00");
			map.put("msg","您的账户优惠券余额不足以支付本次订单");
			return map;
		}
		map.put("code","01");
		map.put("msg","优惠券余额充足");
		return map;
	}

	//第三方支付记录
	public LogThirdpay getLogThirdpay(int userId,String orderNo,String businessType,BigDecimal payMoney,String outTradeNo ){
		LogThirdpay logThirdpay=new LogThirdpay();
		logThirdpay.setUserId(userId);
		logThirdpay.setOrderNo(orderNo);
		logThirdpay.setBusinessType(businessType);
		logThirdpay.setPayMoney(payMoney);
		logThirdpay.setOrderNo(outTradeNo);
		return logThirdpay;
	}
	@Override
	public Map<String,Object> checkShopping(String userIds, BigDecimal mailccMoney){
		Map<String,Object> map=new HashMap<>();
		if (userIds==null|| "".equals(userIds)){
			map.put("code","00");
			map.put("msg","没有登录，请重新登录");
			return map;
		}
		Integer userId=Integer.parseInt(userIds);
		Account account=new Account();
		account.setUserId(userId);
		EntityWrapper<Account> entityWrapper=new  EntityWrapper<Account>(account);
		Account account1 = this.selectOne(entityWrapper);
		BigDecimal mailcc = account1.getShoppingMoney();
		if (mailcc.compareTo(mailccMoney)==-1){
			map.put("code","00");
			map.put("msg","优惠券余额不足无法购买");
			return map;
		}else{
			map.put("code","01");
			map.put("msg","查询成功");
			map.put("shoppingMoney",mailcc);
			return map;
		}
	}
	public SktOrderReview getSktOrderReview(Integer userId,String orderunique,String thirdNo,Integer thirdType,BigDecimal payMoney,BigDecimal payShopping ){
		SktOrderReview sktOrderReview=new SktOrderReview();
		sktOrderReview.setUserId(userId);
		sktOrderReview.setOrderunique(orderunique);
		sktOrderReview.setOutTradeNo(thirdNo);
		sktOrderReview.setOrderStatus(0);
		sktOrderReview.setIsPay(1);
		sktOrderReview.setPayType(thirdType);
		sktOrderReview.setPayMoney(payMoney);
		sktOrderReview.setPayShopping(payShopping);
		sktOrderReview.setDataFlag(1);
		sktOrderReview.setCreateTime(new Date());
		return sktOrderReview;
	}


}
